Linux如何复制而不覆盖?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9392735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:44:54  来源:igfitidea点击:

Linux how to copy but not overwrite?

linuxbashcp

提问by mnowotka

I want to cpa 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?

我想要cp一个目录,但我不想覆盖任何现有文件,即使它们比复制的文件旧。我想完全非交互式地完成它,因为这将是 Crontab Bash 脚本的一部分。有任何想法吗?

采纳答案by 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

回答by bucko

cp -n

Is what you want. See the man page.

是你想要的。请参阅手册页。

回答by Grim...

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

对于那些发现没有 'n' 选项的人(就像我在 RedHat 上的),您可以使用cp -u仅在源比现有源更新(或没有现有源)时才写入文件。

[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.

[编辑] 正如评论中提到的,这将覆盖旧文件,所以这不是 OP 想要的。为此,请使用 ceving 的答案。

回答by ceving

This will work on RedHat:

这将适用于 RedHat:

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

Updatingand not overwritingis something different.

更新不覆盖是不同的。

回答by Hans Ginzel

Consider using rsync.

考虑使用rsync.

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


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

根据评论rsync -a -v src dst不正确,因为它会更新现有文件。

回答by Kamil Kie?czewski

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

Alpine linux:以下答案仅适用于单个文件的情况:在 alpine 中cp -n不工作(以及false | cp -i ...)所以我发现的解决方案在我的情况下是:

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

In above example if env.jsfile not exists then we copy env.example.jsto env.js.

在上面的例子中,如果env.js文件不存在,那么我们复制env.example.jsenv.js.

回答by Octavian

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

某些版本的 cp 没有--no-clobber选项。在这种情况下:

  echo n | cp -vipr src/* dst