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?
To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...] arg1 arg2 ...'
Sample shell script to display the current date and time #!/bin/bash now="$(date)" printf "Current date and time %s\n" "$now" now="$(date +'%d/%m/%Y')" printf "Current date in dd/mm/yyyy format %s\n" "$now" echo "Starting backup at $now, please wait..." # command to backup scripts goes here # ...
To get get result of command you need to use command substitution (bash feature). Command substitution provides executing a bash command/commands and store its output to variable. You can use special backticks (``). Everything what you write between backticks is executed by the shell before main command is executed.
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With