7

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?

2 Answers 2

8

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:

  • no need to escape backslashes,
  • you can nest commands without escaping backticks.

Description of the differences: Bash Command Substition

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.