在 Bash 中找不到文件时如何使 cp 命令安静?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25337405/
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
How to make cp command quiet when no file is found in Bash?
提问by Village
I searched map cp
, but can find no quiet option, so that cp
does not report "No such file or directory".
我搜索过map cp
,但找不到安静选项,因此cp
不会报告“没有这样的文件或目录”。
How can I make cp
not print this error if it attempts, but fails, to copy the file?
cp
如果尝试复制文件但失败,如何不打印此错误?
回答by jaypal singh
Well everyone has suggested that redirecting to /dev/null
would prevent you from seeing the error, but here is another way. Test if the file exists and if it does, execute the cp
command.
好吧,每个人都建议重定向到/dev/null
会阻止您看到错误,但这是另一种方式。测试文件是否存在,如果存在,执行cp
命令。
[[ -e f.txt ]] && cp f.txt ff.txt
In this case, if the first test fails, then cp
will never run and hence no error.
在这种情况下,如果第一个测试失败,则cp
永远不会运行,因此不会出现错误。
回答by askmish
If you want to suppress just the error messages:
如果您只想抑制错误消息:
cp original.txt copy.txt 2>/dev/null
If you want to suppress bot the error messages and the exit code use:
如果要抑制机器人错误消息和退出代码,请使用:
cp original.txt copy.txt 2>/dev/null || :
回答by rici
The general solution is to redirect stderr to the bitbucket:
一般的解决方案是将 stderr 重定向到 bitbucket:
cp old_file new_file 2>>/dev/null
Doing so will hide any bugs in your script, which means that it will silently fail in various circumstances. I use >>
rather than >
in the redirect in case it's necessary to use a log file instead.
这样做会隐藏脚本中的任何错误,这意味着它会在各种情况下默默地失败。我在重定向中使用>>
而不是>
在需要使用日志文件的情况下。
回答by sschuberth
回答by konsolebox
Redirect:
重定向:
cp ... 2>/dev/null
回答by Upen
rsync -avzh --ignore-missing-args /path/to/source /path/to/destination
ignore-missing-args
: errors ignored are those related to source files not existing
ignore-missing-args
: 忽略的错误是与不存在的源文件相关的错误