在 bash 中隐藏错误消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25348142/
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-18 11:09:43  来源:igfitidea点击:

Hide error message in bash

bashshell

提问by VincentHuang

I have problem to hide error message from shell command as the following case.

在以下情况下,我无法从 shell 命令隐藏错误消息。

firs_line=$(head -n 1 file) > /dev/null 2>&1

I expect that the error message will be hidden but actually it doesn't. How to get output while headcommand is executed successfully but hide error message when it fails?

我希望错误消息会被隐藏,但实际上并没有。如何在head命令成功执行时获取输出但在失败时隐藏错误消息?

Thanks in advance.

提前致谢。

回答by pqnet

Is the error message coming from the headprogram (like, file not found)?

错误消息是否来自head程序(例如未找到文件)?

In this case you have to redirect the output from inside parens:

在这种情况下,您必须从括号内重定向输出:

firs_line=$(head -n 1 file 2>/dev/null)

Moreover, you only have to redirect standard error (and not standard output which is supposed to be catched by $()to be stored in firs_line

此外,您只需要重定向标准错误(而不是应该被捕获$()并存储在firs_line

回答by Cyrus

firs_line="$([ -r file ] && head -n 1 file)"