Capturing the output of bash time in script variab

2020-07-09 10:25发布

问题:

I'm trying this:

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

and when I execute I see the number I want in the output but not in variable foo (echo $foo print nothing).

Why is that?

回答1:

You are not capturing anything in foo because time sends its output on stderr. The trouble is that the wget command also sends most of its output on stderr. To split the two streams (and throw away the output from wget) you will need to use a subshell:

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

Here is an explanation of what's going on...

The inner part of this command:

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

Sends both stderr and stdout to /dev/null, essentially throwing them away.

The outer part:

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

Sends stderr from the time command to the same place that stdout is sent so that it may be captured by the command substitution ($()).

Update:

If you wanted to get really clever, you can have the output of wget passed through to stderr by juggling the file descriptors like this:

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