1

I want to avoid my script posting an error if I try to cp a file that does not exist. However, I would like error messages to print out for any other error, such as insufficient permissions. This means I can't send the messages to dev/null. what other solutions are there to do this in a script?

One option is an if statement to check if the file exists before copying, but it seems rather cluttered approach. I think I can get what I want by adding an * in the file's name, though it seems an odd way of doing things. is there some command line argument or other way to get what I want?

  • 1
    "an if statement to check if the file exists before copying" is a reasonable way to go. – Faheem Mitha Dec 19 '14 at 17:57
2

Checking for existence will reduce the problem, but in the most general case it's a race condition. The file could still be removed between the check and the copy attempt.

Perhaps just capture all errors and drop any for "file doesn't exist".

Normal copy:

$ cp noexist bar /tmp
cp: cannot stat `noexist': No such file or directory
cp: cannot open `bar' for reading: Permission denied

Modified

$ cp noexist bar /tmp 2>&1 | grep -v "No such file or directory" >&2
cp: cannot open `bar' for reading: Permission denied
1

You might do like:

{ command <doesntexist cp doesntexist 2>&3 ; } 3>&2 2>/dev/null

It might be shorter in a subshell...

( <file cp file ... 2>&3 ) 3>&2 2>/dev/null

But it still seems like a long way around doing...

[ -r file ] && cp file ...

All of those only test for readable files though - they won't work for directories...

But...

[ -e file ] && cp file ...

...could...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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