Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

capturing standard error into a variable in bash

Tags:

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?

like image 280
nedned Avatar asked Jun 12 '09 01:06

nedned


2 Answers

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

like image 135
Jeremy Wall Avatar answered Sep 20 '22 12:09

Jeremy Wall


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.

like image 39
Eddie Avatar answered Sep 21 '22 12:09

Eddie