将标准错误捕获到 bash 中的变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/984586/
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
capturing standard error into a variable in bash
提问by nedned
I would like to capture the output of the time command (which writes to standard error) into a variable. I know that this can be done like this:
我想将时间命令(写入标准错误)的输出捕获到一个变量中。我知道这可以这样做:
$ var=`time (mycommand &> /dev/null) 2>&1`
$ echo "$var"
real 0m0.003s
user 0m0.001s
sys 0m0.002s
With the innermost redirect sending standard out and standard error of mycommand to /dev/null as it's not needed, and the outermost redirect sending standard error to standard out so that it can be stored in the variable.
最里面的重定向将 mycommand 的标准输出和标准错误发送到 /dev/null ,因为它不需要,而最外面的重定向将标准错误发送到标准输出,以便它可以存储在变量中。
My problem was that I couldn't get this working inside a shell script, but it turns out that it was because of a bug elsewhere. So now that I've gone ahead and written this question, instead I'm going to ask, is this the best way to achieve this or would you do it differently?
我的问题是我无法在 shell 脚本中使用它,但事实证明这是因为其他地方的错误。既然我已经写下了这个问题,那么我要问的是,这是实现这一目标的最佳方式,还是您会采用不同的方式?
回答by Jeremy Wall
The only change I would make is:
我要做的唯一改变是:
var=$(time (mycommand &> /dev/null) 2>&1)
The $()command syntax if you shell supports it is superior for two reasons:
该$()命令语法,如果你的外壳支持它优越的原因有两个:
- no need to escape backslashes,
- you can nest commands without escaping backticks.
- 无需逃避反斜杠,
- 您可以在不转义反引号的情况下嵌套命令。
Description of the differences: Bash Command Substition
差异说明:Bash 命令替换
回答by Eddie
If you truly don't need stdout or stderr from the program being timed, this is a fine way to do this and should be as efficient as any other method.
如果您真的不需要正在计时的程序中的 stdout 或 stderr,这是一个很好的方法,并且应该与任何其他方法一样有效。

