Bash – Using process substitution, only send stderr to process

bashprocess-substitutionshellshell-script

I have this:

exec > >( while read line; do echo " stdout: $line"; done )
exec 2> >( while read line; do echo " stderr: $line"; done )

echo "rolo"
>&2 echo "cholo"

if you run that script, it results in the following output:

stdout: rolo
stdout: stderr: cholo

how can I only send stderr to the second process substitution line?
I don't get it.

I don't understand why this is happening:

stdout: rolo
stdout: stderr: cholo # what lol

Best Answer

You set up the redirections in the wrong order. The standard output of the second process substitution (which prefixes with stderr:) has its standard output prefixed by the first process substitution, because it was run afterwards.

Try this instead:

exec 2> >( while read line; do echo " stderr: $line"; done )
exec > >( while read line; do echo " stdout: $line"; done )

echo "rolo"
echo "cholo" >&2

This outputs

 stderr: cholo
 stdout: rolo

which is what I presume you want.

Related Question