Shell – Make cp return an error value if the target exists

coreutilscpshell-script

Is there a way to make cp (from GNU coreutils on Linux) return a nonzero value in case the target file does already exist?
Or is there any other small utility which is commonly available and which provides this functionality?

This would be useful in shell scripts, to atomically copy a file without accidentially loosing anything, and without user interaction. A similar result can be obtained by comparing the copy against the original, but I would have hoped for a simpler solution.

Best Answer

You could do:

(set -C &&  cat < /path/to/src > /path/to/dest)

It won't copy anything but the content of the file though (not the permissions, ownership or sparseness as some cp implementations do).

Related Question