在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:37:42  来源:igfitidea点击:

How to make cp command quiet when no file is found in Bash?

bashcp

提问by Village

I searched map cp, but can find no quiet option, so that cpdoes not report "No such file or directory".

我搜索过map cp,但找不到安静选项,因此cp不会报告“没有这样的文件或目录”。

How can I make cpnot print this error if it attempts, but fails, to copy the file?

cp如果尝试复制文件但失败,如何不打印此错误?

回答by jaypal singh

Well everyone has suggested that redirecting to /dev/nullwould prevent you from seeing the error, but here is another way. Test if the file exists and if it does, execute the cpcommand.

好吧,每个人都建议重定向到/dev/null会阻止您看到错误,但这是另一种方式。测试文件是否存在,如果存在,执行cp命令。

[[ -e f.txt ]] && cp f.txt ff.txt

In this case, if the first test fails, then cpwill 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

Like for any error printed to STDERR, just redirect it to /dev/null:

就像打印到STDERR 的任何错误一样,只需将其重定向到/dev/null

cp a b 2> /dev/null

回答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: 忽略的错误是与不存在的源文件相关的错误