【问题标题】:Capturing the output of bash time in script variable在脚本变量中捕获 bash 时间的输出
【发布时间】:2012-08-08 16:17:34
【问题描述】:

我正在尝试这个:

TIMEFORMAT=%R;
foo=$(time wget http://www.mysite.com)
echo $foo

当我执行时,我在输出中看到了我想要的数字,但在变量 foo 中没有(echo $foo 什么都不打印)。

这是为什么呢?

【问题讨论】:

标签: bash shell time wget


【解决方案1】:

您没有在foo 中捕获任何内容,因为time 将其输出发送到stderr。问题在于wget 命令还将其大部分输出发送到stderr。要拆分两个流(并丢弃wget 的输出),您需要使用subshell

TIMEFORMAT=%R;
foo=$( time ( wget http://www.example.com 2>/dev/null 1>&2 ) 2>&1 )
echo $foo

这里是对正在发生的事情的解释......

这个命令的内部:

( wget http://www.example.com 2>/dev/null 1>&2 )

stderrstdout 都发送到/dev/null,实际上是把它们扔掉。

外部:

foo=$( time ( ... ) 2>&1 )

time 命令将stderr 发送到发送stdout 的同一位置,以便command substitution ($()) 可以捕获它。

更新:

如果你想变得更聪明,你可以像这样处理文件描述符,将wget 的输出传递给stderr

foo=$( time ( wget http://www.example.com 2>&1 ) 3>&1 1>&2 2>&3 )

【讨论】:

  • 你,@lee-netherton,是个救世主!
猜你喜欢
  • 1970-01-01
  • 2012-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-02
  • 1970-01-01
  • 1970-01-01
  • 2016-10-28
相关资源
最近更新 更多