Linux how to copy but not overwrite?

会有一股神秘感。 提交于 2019-11-28 15:00:31
hovanessyan

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
Hans Ginzel

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.

cp -n

Is what you want. See the man page.

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.

This will work on RedHat:

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

Updating and not overwriting is something different.

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.

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

  echo n | cp -vipr src/* dst
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!