Linux how to copy but not overwrite?
Solution 1
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
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
cp -n
Is what you want. See the man page.
Solution 4
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
This will work on RedHat:
false | cp -i source destination 2>/dev/null
Updating and not overwriting is something different.
mnowotka
Professional Python developer with many years of experience in writing code in Python and C++ and joining them together. Experienced web developer and open source enthusiast. Has academic background in CS but professionally involved in chem and bio informatics. A gentleman, who demands excellence from his code. LinkedIn Profile GitHub repo My presentations
Updated on July 18, 2022Comments
-
mnowotka almost 2 years
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?