How to let 'cp' command don't fire an error when source file does not exist?

Solution 1:

If you're talking about the error message, you can suppress that by sending it to the bit bucket:

cp ./src/*/*.h ./aaa 2>/dev/null

If you want to suppress the exit code and the error message:

cp ./src/*/*.h ./aaa 2>/dev/null || :

Solution 2:

You're looking for something along the lines of

if [ -e file ]
 then cp file /somewhere
fi

(Unfortunately, the -f option is not the droid you're looking for.)

If you want to match a glob, that won't work; use find instead, e.g.:

find ./src -name \*.h -exec cp {} ./destination \;

Solution 3:

Old question, but might still be relevant for others.
If you don't need to use cp, you could try with rsync.
To copy all files from a source to a destination directory, run:

rsync -avzh --ignore-errors /path/to/source /path/to/destination

Rsync comes with most Unix-like systems such as Linux, Mac OS X or FreeBSD.

Solution 4:

Piping the result to true ensures that the command will always succeed. I have tried this on Linux but not on any Mac OS:

cp ./src/*/*.h ./aaa | true

Solution 5:

You could force the correct error status. With a function:

$ cpalways () { cp $1 $2 2>/dev/null ; return 0 ; }

Given the following:

$ ls foo bar baz
ls: baz: No such file or directory
bar foo

Regular copy will return an error. It will return an exit status of 1.

$ cp baz bar ; echo $?
cp: baz: No such file or directory
1

If we use the cpalways() function above, any errors will be hidden:

$ cpalways baz bar ; echo $?
0
$ cpalways foo bar ; echo $?
0
$ cpalways baz bar ; echo $?
0