Tell me more ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

X=$(time ls)

or

$(time ls) | grep real

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

share|improve this question

3 Answers

up vote 9 down vote accepted

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

share|improve this answer

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

Your Answer

 
discard

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.