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. Dec 19 '14 at 17:57

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...


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



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


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

Simply check IF the directory/file already exists:

  • to copy a file

    file=path/to/the/file/to/copy && [ -f "${file}" ] && cp ${file} destination/path/here

  • to copy a directory

    dir=path/to/the/dir/to/copy && [ -d "${dir}" ] && cp -r ${dir} destination/path/here


the spaces before/after the square brackets are mandatory, not to break the above commands.

REFERENCES: https://linuxize.com/post/bash-check-if-file-exists/

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.