cp -a foo/* bar/ will copy the contents of foo into bar, replacing any files that already exist. I can use the -n flag to make cp not overwrite existing files or -i to make it ask interactively whether to overwrite files.


  • Is there a way to make cp fail and return an error code if the file already exists?
  • If not, is it possible to do with rsync or some other common tool?


It's possible to fail if a file exists on Linux, via a slight hack with GNU nohup. nohup redirects /dev/null to stdin so any interactive prompts are ignored, but treats the use of stdin as a failure.

$ nohup cp -ia foo/* bar/

To clean up a little bit:

$ nohup cp -ia foo/* bar/ 2>nohup.out && rm nohup.out || cat nohup.out
  • By default nohup redirects stdout to nohup.out and stderr to stdout.
  • 2>nohup.out puts stderr into the file as well.
  • The && rm || cat will clean up on success or output the error from nohup.out on error. You can add whatever error handling you want instead of/including the cat or remove all of that and deal with $? as normal.
  • You will need to be a bit smarter about the temp file location if you use this in earnest (mktemp -d)


On BSD you can redirect stdin to cp which will be treated as n and return a non 0 status.

$ cp -ia foo/* bar/ </dev/null


On OSX cp behaves differently to BSD, surprisingly, and does return a non 0 status with -n on a skipped file.

$ cp -n foo/* bar/
| improve this answer | |

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.