Store stderr output in bash variable

Linux howto's, compile information, information on whatever we learned on working with linux, MACOs and - of course - Products of the big evil....
Post Reply
User avatar
^rooker
Site Admin
Posts: 1483
Joined: Fri Aug 29, 2003 8:39 pm

Store stderr output in bash variable

Post by ^rooker »

[PROBLEM]
Sometimes I needed to evaluate information output to stderr in a bash script, but how to capture that output?

[SOLUTION]
Luckily, I stumbled over a comment on "stackoverflow" about "redirecting stderr to a variable in a bash script".

The solution is as follows:
Redirect stderr to stdout and redirect stdout to /dev/null.

In Bash-speak, that is:

Code: Select all

cmd="whatever command you want to execute"
ERROR=$($cmd 2>&1 >/dev/null)
echo $ERROR
Jumping out of an airplane is not a basic instinct. Neither is breathing underwater. But put the two together and you're traveling through space!
Post Reply