Linux how to copy but not overwrite?
LinuxBashCpLinux 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