How to tee to stderr?

BashStderrTee

Bash Problem Overview


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?

Bash Solutions


Solution 1 - Bash

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.

Solution 2 - Bash

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

Solution 3 - Bash

./script.sh 2>&1 >/dev/null | tee stderr.out

That opens STDERR to STDOUT, and then disposes of STDOUT.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondjechlinView Question on Stackoverflow
Solution 1 - BashbrianeggeView Answer on Stackoverflow
Solution 2 - BashNicholas WilsonView Answer on Stackoverflow
Solution 3 - BashDavid W.View Answer on Stackoverflow