复制目录,但如果目标文件已存在则失败

Shu*_*hum 3 cp rsync

cp -a foo/* bar/会将 foo 的内容复制到 bar 中,替换任何已存在的文件。我可以使用 -n 标志来cp不覆盖现有文件或-i使其以交互方式询问是否覆盖文件。

问题

  • cp如果文件已经存在,有没有办法使失败并返回错误代码?
  • 如果没有,是否可以使用rsync其他常用工具?

Mat*_*att 5

Linux

如果文件存在于 Linux 上,则通过 GNU 的轻微修改可能会失败nohupnohup重定向/dev/nullstdin,因此任何交互式提示都会被忽略,但将使用视为stdin失败。

$ nohup cp -ia foo/* bar/
Run Code Online (Sandbox Code Playgroud)

清理一下:

$ nohup cp -ia foo/* bar/ 2>nohup.out && rm nohup.out || cat nohup.out
Run Code Online (Sandbox Code Playgroud)
  • 默认情况下nohup重定向stdoutnohup.out和。stderrstdout
  • 2>nohup.outstderr也放入文件中。
  • 将在成功时清除或在错误时&& rm || cat输出错误。nohup.out您可以添加任何您想要的错误处理,而不是/包括cat或删除所有这些并$?正常处理。
  • 如果您认真使用它,您将需要对临时文件位置更加了解 ( mktemp -d)

BSD

在 BSD 上,您可以重定向stdincp将被视为n并返回非 0 状态的位置。

$ cp -ia foo/* bar/ </dev/null
Run Code Online (Sandbox Code Playgroud)

操作系统X

令人惊讶的是,OSX 上的cp行为与 BSD 不同,并且确实会-n在跳过的文件上返回非 0 状态。

$ cp -n foo/* bar/
Run Code Online (Sandbox Code Playgroud)