8

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

2 Answers 2

14

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 )
Sign up to request clarification or add additional context in comments.

1 Comment

You, @lee-netherton, are a saviour!
0

I needed to do the following to capture the output of time:

~$ var=$({ TIMEFORMAT=%R; time sleep 1; } 2>&1)
~$ echo $var
1.001

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.