A brute force method by let tee listen on both stderr and stdout is okay like
cmd 2>&1 | tee -a log
But how to make tee catch the stderr only?
You can make use of “process substitution” (
>(...)) to creates a FIFO to catch the STDERR and pass it to
Lets take an example t.sh:
#!/bin/bash echo hello 1>&2 echo world
It works as expected:
$ ./t.sh hello world $ ./t.sh >/dev/null world $ ./t.sh 2>/dev/null hello
Now, let’s redirect the STDERR to
$ ./t.sh 2> >(tee /tmp/log) hello $ world cat /tmp/log world
tee prints to STDOUT by default. Let’s make it print to STDERR:
$ ./t.sh 2> >(tee /tmp/log >&2) hello world $ cat /tmp/log world
$ (./t.sh 2> >(tee /tmp/log >&2) ) >/dev/null world
The “world” is not to the STDOUT anymore.