Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tee to stderr?

Tags:

bash

stderr

tee

I want to split stdout so that it is printed both to stdout and stderr. This sounds like a job for tee but the syntax is evading me -

./script.sh | tee stderr

Of course, how should stderr actually be referred to here?

like image 829
djechlin Avatar asked Dec 10 '12 16:12

djechlin


People also ask

Does tee catch stderr?

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

What is the meaning of 2 >& 1?

The 1 denotes standard output (stdout). The 2 denotes standard error (stderr). So 2>&1 says to send standard error to where ever standard output is being redirected as well.

Can you read from stderr?

STDERR_FILENO is an output file descriptor. You can't read from it.


2 Answers

The only cross platform method I found which works in both interactive and non-interactive shells is:

command | tee >(cat 1>&2)

The argument to tee is a file or file handle. Using process substitution we send the output to a process. In the process =cat=, we redirect stdout to stderr. The shell (bash/ksh) is responsible for setting up the 1 and 2 file descriptors.

like image 160
brianegge Avatar answered Oct 20 '22 02:10

brianegge


./script.sh | tee /dev/fd/2

Note that this is dependant on OS support, not any built-in power in tee, so isn't universal (but will work on MacOS, Linux, Solaris, FreeBSD, probably others).

like image 59
Nicholas Wilson Avatar answered Oct 20 '22 02:10

Nicholas Wilson