bash - 在脚本变量中捕获 bash 时间的输出

标签 bash shell time wget

我正在尝试这个:

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

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

这是为什么?

最佳答案

您没有在 foo 中捕获任何内容,因为 timestderr 上发送它的输出。问题在于 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 )

关于bash - 在脚本变量中捕获 bash 时间的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11868811/

相关文章:

python - 命令 "pipenv run"昨天工作正常。为什么我今天收到 AttributeError?

objective-c - 如何准确测量时间差xcode

bash - 确定终端格式化输出的能力?

c - 如何防止在 fgets 中回显一些字符

shell - 如何复制终端的输出并将它们粘贴到输入中?

shell - cat 文件和 shell 脚本中的新行

git - 如何从终端或命令行创建 gitlab 项目

linux - Bash 脚本在 if elif else 语句中包含逻辑与和或

比较文件的 Bash 脚本

java - 通过获取当前时间进行SQL查询