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:
我想将time命令的输出(写入标准错误)捕获到变量中。我知道这可以这样做:
$ 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脚本中使用它,但事实证明这是因为其他地方的错误。所以现在我已经开始写这个问题,而不是我要问,这是实现这个目标的最佳方式还是你会采用不同的方式?
2 个解决方案
#1
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:
如果shell支持它的$()命令语法是优越的,原因有两个:
- no need to escape backslashes,
- you can nest commands without escaping backticks.
无需逃避反斜杠,
你可以在不转义反引号的情况下嵌套命令。
Description of the differences: Bash Command Substition
差异描述:Bash命令替换
#2
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,这是一个很好的方法,并且应该像任何其他方法一样高效。
#1
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:
如果shell支持它的$()命令语法是优越的,原因有两个:
- no need to escape backslashes,
- you can nest commands without escaping backticks.
无需逃避反斜杠,
你可以在不转义反引号的情况下嵌套命令。
Description of the differences: Bash Command Substition
差异描述:Bash命令替换
#2
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,这是一个很好的方法,并且应该像任何其他方法一样高效。