With bash, how can I pipe standard error into another process?
You can use the following trick to swap stdout
and stderr
. Then you just use the regular pipe functionality.
( proc1 3>&1 1>&2- 2>&3- ) | proc2
Provided stdout
and stderr
both pointed to the same place at the start, this will give you what you need.
What the x>&y
bit does is to change file handle x
so it now sends its data to wherever file handle y
currently points. For our specific case:
3>&1
creates a new handle3
which will output to the current handle1
(original stdout), just to save it somewhere for the final bullet point below.1>&2
modifies handle1
(stdout) to output to the current handle2
(original stderr).2>&3-
modifies handle2
(stderr) to output to the current handle3
(original stdout) then closes handle3
(via the-
at the end).
It's effectively the swap command you see in sorting algorithms:
temp = value1;
value1 = value2;
value2 = temp;
There is also process substitution. Which makes a process substitute for a file.
You can send stderr
to a file as follows:
process1 2> file
But you can substitute a process for the file as follows:
process1 2> >(process2)
Here is a concrete example that sends stderr
to both the screen and appends to a logfile
sh myscript 2> >(tee -a errlog)