我只想捕获一个时间命令的输出,即:
X=$(time ls)
要么
$(time ls) | grep real
时间函数吐到控制台。 我如何做到这一点?
X =`(时间ls)2>&1 | grep真正`
见BashFAQ / 032 。
$ # captures output of command and time $ time=$( TIMEFORMAT="%R"; { time ls; } 2>&1 ) # note the curly braces $ # captures the time only, passes stdout through $ exec 3>&1 4>&2 $ time=$(TIMEFORMAT="%R"; { time ls 1>&3 2>&4; } 2>&1) bar baz $ exec 3>&- 4>&-
时间将看起来像“0.000”使用TIMEFORMAT="%R"这将是“真实”的时间。
时间将其输出写入STDERR而不是STDOUT。 更糟糕的是,默认情况下'time'是一个shell内置命令,所以如果你尝试'time ls 2>&1','2&1'只适用于'ls'。
解决scheme可能是这样的:
/usr/bin/time -f 'real %e' -o OUTPUT_FILE ls > /dev/null 2>&1<br> REALTIME=$(cat OUTPUT_FILE | cut -f 2 -d ' ')
有更多奇特的方法来做到这一点,但这是明确/简单的方法。