Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I'm using Mac OS X. I'm trying to copying some files with cp command for a build script like this.

cp ./src/*/*.h ./aaa

But this command fires an error if there is no .h file in ./src directory. How to make the command don't fire the error? (silent failure) The error makes build result fail, but I just want to copy when only there are some header file.

share|improve this question

3 Answers 3

up vote 8 down vote accepted

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 || :
share|improve this answer
    
It would be nice to explain what : means in this context. –  Piotr Dobrogost Feb 10 at 15:35
3  
@PiotrDobrogost: In Bash and some other shells the colon is a null utility (no-op). It's specified by POSIX. Since it always returns true, it's used here to suppress the exit code of a failed cp (should that be desired). The shell builtin true could be used instead and would be more readable. –  Dennis Williamson Feb 10 at 15:46
    

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 \;
share|improve this answer

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.