Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I just want to capture the output of a time command i.e:

X=$(time ls)


$(time ls) | grep real

The time function spits it to the console though. How do I do this?

share|improve this question
up vote 10 down vote accepted

X=`(time ls) 2>&1 | grep real`

share|improve this answer
You don't need a subshell just for time; Dennis Williamson's answer is better in that regard. – musiphil Nov 1 '13 at 21:32

See 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>&-

The time will look like "0.000" using TIMEFORMAT="%R" which will be the "real" time.

share|improve this answer

Time writes its output to STDERR rather than STDOUT. Making matters worse, by default 'time' is a shell builtin command, so if you attempt 'time ls 2>&1' the '2>&1' only applies to 'ls'.

The solution would probably be something like:

/usr/bin/time -f 'real %e' -o OUTPUT_FILE ls > /dev/null 2>&1<br>
REALTIME=$(cat OUTPUT_FILE | cut -f 2 -d ' ')

There are more fancy ways to do it, but that is the clear/simple way.

share|improve this answer
I am interested in doing this without -o. Can you post one of the fancy methods you were thinking of :) ? – David Doria Apr 22 '14 at 17:12

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.