问题
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?
回答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
回答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.
回答3:
cp -n
Is what you want. See the man page.
回答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.
回答5:
This will work on RedHat:
false | cp -i source destination 2>/dev/null
Updating and not overwriting is something different.
回答6:
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
.
回答7:
Some version of cp do not have the --no-clobber option. In that case:
echo n | cp -vipr src/* dst
来源:https://stackoverflow.com/questions/9392735/linux-how-to-copy-but-not-overwrite