LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   How to get stderr and stdout of a program into separate env variables? (https://www.linuxquestions.org/questions/linux-software-2/how-to-get-stderr-and-stdout-of-a-program-into-separate-env-variables-808853/)

10110111 05-19-2010 09:38 AM

How to get stderr and stdout of a program into separate env variables?
 
I'm looking for a more efficient way of doing something like this:
Code:

MY_STDOUT=`my-command`
MY_STDERR=`my-command >&2`

That is, i want to have to run my-command only once and get the same result.
I've tried this:
Code:

YYY=$(XXX=`{ echo -n 111; echo 222 >&2; }` 2>&1); echo $XXX $YYY
where "{ echo -n 111; echo 222 >&2; }" is my-command. But it gives this output:
Code:

222
111

instead of "111 222".
What's wrong in my script? Maybe there exists a nicer way of doing this?

rweaver 05-19-2010 03:35 PM

First lets establish some basic behavior...

test.sh
Code:

#!/bin/bash
echo "STDOUT"
echo "STDERR" 1>&2

Code:

core$ ./test.sh
STDOUT
STDERR
core$ ./test.sh 2> STDERR.txt
STDOUT
core$ ./test.sh 1> STDOUT.txt
STDERR
core$ cat STDERR.txt
STDERR
core$ cat STDOUT.txt
STDOUT

So at this point we know and can prove our basic script outputs one line to stderr and one line to stdout. You might want to use something like this for testing because sometimes behavior does change from executing several commands to calling another program due to redirection and piping.

This--

Code:

YYY=$(XXX=`{ echo -n 111; echo 222 >&2; }` 2>&1); echo $XXX $YYY
only gives me 222, which is not being echo'd at all but is being displayed on stderr... you get same result removing the echo as having it. You can tell where your stuff is coming from by redirecting the stream to a file 1>file or 2>file.

The real problem you're having here is scoping. the XXX is being lost when it returns from calling out no matter what else you do.

catkin 05-20-2010 06:17 AM

Backing up what rweaver wrote, as it says in the Bash FAQ: "What you cannot do is capture stdout in one variable, and stderr in another, using only FD redirections. You must use a temporary file to achieve that one".


All times are GMT -5. The time now is 01:46 PM.