Saving STDERR to a variable

Getting the (standard) output of a command into a variable (and leaving any errors to go to the display) is simple:

var=`command`

or, as some people prefer:

var=$(command)

In either case echo $var will then show you what was sent to STDERR.

However sometimes you want to get the "error" messages into the variable and leave the normal output displayed on the screen. I say "error" in quotation marks because utilities like time show their own output on standard error STDERR whilst leaving the output of the command being timed going to standard output STDOUT.

In this case the method is what I would call "simple, but obscure":

{ stderr=$(command 2>&1 >&3 3>&-); } 3>&1

So, for the specific use case of timing a command and then being able to use the duration afterwards:

{ t=$(/usr/bin/time -f %E command 2>&1 >&3 3>&-); } 3>&1
echo "Time taken = $t"

If you actually want to redirect the standard output to a file at the same time, simply change the 3>&1 at the end to 3>/filename

Thanks to https://unix.stackexchange.com/questions/474177 for this bit of bash expertise.


Go up
Return to main index.