views:

45

answers:

3

Is there any way, in bash, to pipe stderr through a filter before unifying it with stdout? That is, I want

stdout ----------------\
                        |-----> terminal/file/whatever
stderr -- [ filter ] --/

rather than

stdout ----\
            |----[ filter ]---> terminal/file/whatever
stderr ----/
+2  A: 

The last part of this page of the Advanced Bash Scripting Guide is "redirecting only stderr to a pipe". This may be what you want. If not, some other part of the ABSG should be able to help you, it is excellent.

signine
A: 

Take a look at named pipes:

$ mkfifo err
$ cmd1 2>err |cat - err |cmd2
wilhelmtell
won't `cat - err` break the interspersing of stdout and stderr?
Martin DeMello
@Martin - it depends. If cmd1, cat, **or** cmd2 buffers output, then you could see output out of sequence.
mobrule
+4  A: 

Here's an example, modeled after how to swap file descriptors in bash . The output of a.out is the following, without the 'STDXXX: ' prefix.

STDERR: stderr output
STDOUT: more regular

./a.out 3>&1 1>&2 2>&3 3>&- | sed 's/e/E/g'
more regular
stdErr output

Quoting from the above link:

  1. First save stdout as &3 (&1 is duped into 3).
  2. Next send stdout to stderr (&2 is duped into 1).
  3. Send stderr to &3 (stdout) (&3 is duped into 2).
  4. close &3 (&- is duped into 3)
Paul Rubel
Additional reference: [BashFAQ/047](http://mywiki.wooledge.org/BashFAQ/047)
Dennis Williamson