I would like to capture the output of the time command (which writes to standard error) into a variable. I know that this can be done like this:
$ var=`time (mycommand &> /dev/null) 2>&1` $ echo "$var" real 0m0.003s user 0m0.001s sys 0m0.002s
With the innermost redirect sending standard out and standard error of mycommand to /dev/null as it's not needed, and the outermost redirect sending standard error to standard out so that it can be stored in the variable.
My problem was that I couldn't get this working inside a shell script, but it turns out that it was because of a bug elsewhere. So now that I've gone ahead and written this question, instead I'm going to ask, is this the best way to achieve this or would you do it differently?
The only change I would make is:
var=$(time (mycommand &> /dev/null) 2>&1)
The $()
command syntax if you shell supports it is superior for two reasons:
Description of the differences: Bash Command Substition
If you truly don't need stdout or stderr from the program being timed, this is a fine way to do this and should be as efficient as any other method.
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