Pipelines stderr and stdout separately

I would like to do different things for stdout and stderr of a specific command. Sort of

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 normal if stderr from each command gets into my stderr commands, but it’s even better if stderr can be strictly from cmd. I was looking for some kind of syntax that can support this, but I can not find anything.

+4
source share
3 answers

You can use 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 use a process replacement :

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

, stdout stderr cmd.

+4

:

cmd 2> >(stderr_1 | stderr_2) | stdout_1 | stdout_2
+3

The simplest solution would be something like this:

(cmd | gets_stdout) 2>&1 | gets_stderr

The main drawback is that if it gets_stdoutitself has any output on stdout, it will also go to gets_stderr. If this is a problem, you should use one of the answers of anubhava or Kevin.

0
source

Source: https://habr.com/ru/post/1569179/


All Articles