Posts Tagged ‘shell’

* How to redirect stdout to one pipe and stderr to another in bash or bourne shell

Posted on August 11th, 2017 by whinger. Filed under Tech.

So I couldn’t find an answer to this when I searched for it… how can I redirect stdout to one pipe and stderr to another?

In my head, it seems like you should be able to do

mycommand |stdoutpipecmd 2|stderrpipecmd

but you can’t.

There are many answers knocking around stackexchange that seem to not-quite do what I wanted, plus in bash you can apparently do command-redirection with 2>(stderrpipecmd); however I was using bourne shell (embedded system) so that didn’t help me.


Of course the answer is really ridiculously simple: simply encapsulate the redirect into a subshell, and redirect the stderr of the subshell into stdout and pipe that.


( mycommand | stdoutpipecmd ) 2>&1 | stderrpipecmd

It’s really that simple.


If you want to make the result of stdoutpipecmd not be piped through stderrpipecmd (you probably don’t), you can do


( mycommand | stdoutpipecmd 1>&3 ) 3>&2 2>&1 | stderrpipecmd

which will pipe the output from stdoutpipecmd to stderr, while the output from stderrpipecmd will be on stdout.

To fix that, so the output from stdoutpipecmd ends up back on stdout while the output from stderrpipecmd is on stderr, it gets a bit messier:

( ( mycommand | stdoutpipecmd 1>&3 ) 2>&1 | stderrpipecmd ) 3>&1 1>&2

What fun 🙂

Tags: , , , .