3

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.

Questions

  • 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?

1 Answer 1

5

Linux

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)

BSD

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

OSX

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/

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .