How to make tee catch the stderr only in Linux?

I would like to make tee catch the stderr and log it into a file.

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?

asked Oct 8, 2016 by anonymous

1 Answer

You can make use of "process substitution" (>(...)) to creates a FIFO to catch the STDERR and pass it to tee.

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 tee:

$ ./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

Verify it:

$ (./t.sh 2> >(tee /tmp/log >&2) ) >/dev/null
world

The "world" is not to the STDOUT anymore.

answered Oct 18, 2016 by Eric Z Ma (44,280 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...