Writing a standard error into a variable in bash

I would like to capture the output of a time command (which is written to a standard error) into a variable. I know that this can be done as follows:

  $ var = `time (mycommand &> / dev / null) 2> & 1`
     $ echo "$ var"
     real 0m0.003s
     user 0m0.001s
     sys 0m0.002s

With the most internal redirection of sending standard output and the standard mycommand error to / dev / null, since this is not required, and the most external redirects sending the standard error to the standard version so that it can be saved in a variable.

My problem was that I could not get this work to work inside the shell script, but it turned out that it was due to an error elsewhere. So, now that I have gone ahead and written this question, I'm going to ask instead, is this the best way to achieve this, or will you do it differently?

+6
bash
source share
2 answers

The only change I would make:

var=$(time (mycommand &> /dev/null) 2>&1) 

The syntax of the $() command, if you support the shell, is superior for two reasons:

  • No need to hide the backslash,
  • you can embed commands without escaping backlinks.

Description of differences: Bash Command line

+8
source share

Unless you really need stdout or stderr from a program to be synchronized, this is a great way to do this and should be as effective as any other method.

+1
source share

All Articles