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
Linux how to copy but not overwrite?
提问by mnowotka
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?
我想要cp
一个目录,但我不想覆盖任何现有文件,即使它们比复制的文件旧。我想完全非交互式地完成它,因为这将是 Crontab Bash 脚本的一部分。有任何想法吗?
采纳答案by hovanessyan
回答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 -u
to 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
回答by Kamil Kie?czewski
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:
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.js
file not exists then we copy env.example.js
to env.js
.
在上面的例子中,如果env.js
文件不存在,那么我们复制env.example.js
到env.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