How to store standard error in a variable


Let's say I have a script like the following:

echo "This Is Error" 1>&2
echo "This Is Output" 

And I have another shell script:

./ | sed 's/Output/Useless/'

I want to capture "This Is Error", or any other stderr from, into a variable. Let's call it ERROR.

Notice that I am using stdout for something. I want to continue using stdout, so redirecting stderr into stdout is not helpful, in this case.

So, basically, I want to do

./ 2> $ERROR | ...

but that obviously doesn't work.

I also know that I could do

./ 2> /tmp/Error
ERROR=`cat /tmp/Error`

but that's ugly and unnecessary.

Unfortunately, if no answers turn up here that's what I'm going to have to do.

I'm hoping there's another way.

Anyone have any better ideas?

2/19/2019 7:38:48 AM

Accepted Answer

It would be neater to capture the error file thus:


The shell recognizes this and doesn't have to run 'cat' to get the data.

The bigger question is hard. I don't think there's an easy way to do it. You'd have to build the entire pipeline into the sub-shell, eventually sending its final standard output to a file, so that you can redirect the errors to standard output.

ERROR=$( { ./ | sed s/Output/Useless/ > outfile; } 2>&1 )

Note that the semi-colon is needed (in classic shells - Bourne, Korn - for sure; probably in Bash too). The '{}' does I/O redirection over the enclosed commands. As written, it would capture errors from sed too.

WARNING: Formally untested code - use at own risk.

2/12/2019 10:17:15 AM

This will allow you to pipe the output of your script through a command such as sed and save the stderr in a variable named error. The result of the pipe is sent to stdout for display or to be piped into another command.

It sets up a couple of extra file descriptors to manage the redirections needed in order to do this.


exec 3>&1 4>&2 #set up extra file descriptors

error=$( { ./ | sed 's/Output/Useless/' 2>&4 1>&3; } 2>&1 )

echo "The message is \"${error}.\""

exec 3>&- 4>&- # release the extra file descriptors

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow