Re: Bash question - redirect stderr to a variable

Top Page
Attachments:
Message as email
+ (text/plain)
+ (text/plain)
Delete this message
Reply to this message
Author: der.hans
Date:  
To: Main PLUG discussion list
Subject: Re: Bash question - redirect stderr to a variable
Am 14. Mar, 2011 schwätzte Bryan O'Neal so:

moin moin,

> Ok - if I want to direct stranded out, standard error, or both to a


Gotta love stranded out :).

> file I can do that. If I want to redirect standard out to a variable
> for latter use, I can do that. But how do I redirect standard error to
> a variable?


If all else fails, you can redirect STDERR to STDOUT, '2>&1'.

If you control whatever's giving the errors you can have it set variables
that are used later.

As to capturing both to variables without using a temporary file, see the
bottom of the following page.

http://mywiki.wooledge.org/BashFAQ/002

If you can do everything you need for one of them in a subshell, then it
is possible.

( exec 3>&1; fred=$( { output=$( ls -d /tmp /ztmp 2>&1 1>&3- ); } 3>&1;
echo "{$output}" | sed -re 's,/ztmp (.+),/zztop \1,'; ); echo "<$fred>"

( exec 3>&1; fred=$( { output=$( ls -d /tmp /ztmp 2>&1 1>&3- ); } 3>&1;
echo "{$output}" | sed -re 's,/ztmp (.+),/zztop \1,' >&2; ); echo
"<$fred>" )
{ls: Zugriff auf /zztop nicht möglich: Datei oder Verzeichnis nicht gefunden}
</tmp>

The sed is just to show that I'm mangling the STDERR output once it's been
tossed into a variable.

Since $output is in a subshell you can't get to it from the normal shell,
but you could call a fx() to handle the data.

( mungestderr() { echo "{$output}" | sed -re 's,/ztmp (.+),/zztop \1,'; };
exec 3>&1; fred=$( { output=$( ls -d /tmp /ztmp 2>&1 1>&3- ); } 3>&1;
mungestderr "$output" ); echo "<$fred>" )
</tmp
{ls: Zugriff auf /zztop nicht möglich: Datei oder Verzeichnis nicht gefunden}>

( mungestderr() { echo "{$output}" | sed -re 's,/ztmp (.+),/zztop \1,' >&2; }; exec 3>&1; fred=$( { output=$( ls -d /tmp /ztmp 2>&1 1>&3- ); } >3>&1; mungestderr "$output" ); echo "<$fred>" )
{ls: Zugriff auf /zztop nicht möglich: Datei oder Verzeichnis nicht gefunden}
</tmp>

To keep it clear you might just want to toss it into a file or named pipe.

ciao,

der.hans
-- 
#  http://www.LuftHans.com/        http://www.LuftHans.com/Classes/
#  ABLEconf - 2011Apr02 - Free Software for Free Enterprise
#  "Backups are irrelevant. Only restorals matter." -- der.hans
---------------------------------------------------
PLUG-discuss mailing list -
To subscribe, unsubscribe, or to change your mail settings:
http://lists.PLUG.phoenix.az.us/mailman/listinfo/plug-discuss