How to make cp command quiet when no file is found in Bash? How to make cp command quiet when no file is found in Bash? bash bash

How to make cp command quiet when no file is found in Bash?


Well everyone has suggested that redirecting to /dev/null would prevent you from seeing the error, but here is another way. Test if the file exists and if it does, execute the cp command.

[[ -e f.txt ]] && cp f.txt ff.txt

In this case, if the first test fails, then cp will never run and hence no error.


If you want to suppress just the error messages:

cp original.txt copy.txt 2>/dev/null

If you want to suppress bot the error messages and the exit code use:

cp original.txt copy.txt 2>/dev/null || :


The general solution is to redirect stderr to the bitbucket:

 cp old_file new_file 2>>/dev/null

Doing so will hide any bugs in your script, which means that it will silently fail in various circumstances. I use >> rather than > in the redirect in case it's necessary to use a log file instead.