Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

piping stderr and stdout separately

Tags:

bash

shell

I'd like to do different things to the stdout and stderr of a particular command. Something like

cmd |1 stdout_1 | stdout_2 |2 stderr_1 | stderr_2

where stdout_x is a command specifically for stdout and stderr_x is specifically for stderr. It's okay if stderr from every command gets piped into my stderr commands, but it's even better if the stderr could be strictly from cmd. I've been searching for some syntax that may support this, but I can't seem to find anything.

like image 978
lucasem Avatar asked Mar 17 '23 12:03

lucasem


1 Answers

You can make use of a different file descriptor:

{ cmd 2>&3 | stdout_1; } 3>&1 1>&2 | stderr_1

Example:

{ { echo 'out'; echo >&2 'error'; } 2>&3 | awk '{print "stdout: " $0}'; } 3>&1 1>&2 |
  awk '{print "stderr: " $0}'
stderr: error
stdout: out

Or else use process substitution:

cmd 2> >(stderr_1) > >(stdout_1)

Example:

{ echo 'out'; echo >&2 'error'; } 2> >(awk '{print "stderr: " $0}') \
> >(awk '{print "stdout: " $0}')
stderr: error
stdout: out

to pipe stdout and stderr separately from your cmd.

like image 117
anubhava Avatar answered Mar 24 '23 08:03

anubhava