How to store standard error in a variable

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

useless.sh

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

And I have another shell script:

alsoUseless.sh

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

I want to capture “This Is Error”, or any other stderr from useless.sh, 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

./useless.sh 2> $ERROR | ...

but that obviously doesn’t work.

I also know that I could do

./useless.sh 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?

20 Answers
20

Leave a Comment