Linux how to copy but not overwrite?

LinuxBashCp

Linux Problem Overview


I want to cp a directory but I do not want to overwrite any existing files even it they are older than the copied files. And I want to do it completely noninteractive as this will be a part of a Crontab Bash script. Any ideas?

Linux Solutions


Solution 1 - Linux

Taken from the man page:

-n, --no-clobber
              do not overwrite an existing file (overrides a previous -i option)

Example:

cp -n myoldfile.txt mycopiedfile.txt

Solution 2 - Linux

Consider using rsync.

rsync -a -v --ignore-existing src dst

As per comments rsync -a -v src dst is not correct because it will update existing files.

Solution 3 - Linux

cp -n

Is what you want. See the man page.

Solution 4 - Linux

For people that find that don't have an 'n' option (like me on RedHat) you can use cp -u to only write the file if the source is newer than the existing one (or there isn't an existing one).

[edit] As mentioned in the comments, this will overwrite older files, so isn't exactly what the OP wanted. Use ceving's answer for that.

Solution 5 - Linux

This will work on RedHat:

false | cp -i source destination 2>/dev/null

Updating and not overwriting is something different.

Solution 6 - Linux

Alpine linux: Below answer is only for case of single file: in alpine cp -n not working (and false | cp -i ... too) so solution working in my case that I found is:

if [ ! -f env.js ]; then cp env.example.js env.js; fi 

In above example if env.js file not exists then we copy env.example.js to env.js.

Solution 7 - Linux

Some version of cp do not have the --no-clobber option. In that case:

  echo n | cp -vipr src/* dst

Solution 8 - Linux

This works for me yes n | cp -i src dest

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmnowotkaView Question on Stackoverflow
Solution 1 - LinuxhovanessyanView Answer on Stackoverflow
Solution 2 - LinuxHans GinzelView Answer on Stackoverflow
Solution 3 - LinuxbuckoView Answer on Stackoverflow
Solution 4 - LinuxGrim...View Answer on Stackoverflow
Solution 5 - LinuxcevingView Answer on Stackoverflow
Solution 6 - LinuxKamil KiełczewskiView Answer on Stackoverflow
Solution 7 - LinuxShōgun8View Answer on Stackoverflow
Solution 8 - LinuxCipherXENView Answer on Stackoverflow