nedned
nedned

Reputation: 3707

capturing standard error into a variable in bash

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?

Upvotes: 7

Views: 8724

Answers (2)

Jeremy Wall
Jeremy Wall

Reputation: 25255

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

Upvotes: 8

Eddie
Eddie

Reputation: 54431

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.

Upvotes: 1

Related Questions