Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing the output of bash time in script variable

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?

like image 859
user967722 Avatar asked Aug 08 '12 16:08

user967722


People also ask

How do you store output of a shell script in a variable?

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 ...'

How do I display date and time in bash?

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 # ...

How do you record the output of a command in a bash script?

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.


1 Answers

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 )
like image 141
Lee Netherton Avatar answered Oct 06 '22 23:10

Lee Netherton