I'm unclear what the best order is to capture both STDERR and STDOUT to the same file using tee. I know that if I want to pipe to a file I have to map the filehandle after the redirect, i.e.

find . >/tmp/output.txt 2>&1

This instructs the shell to send STDOUT to /tmp/output.txt and then to send STDERR to STDOUT (which is now sending to /tmp/output.txt).

Attempting to perform the 2>&1 before redirecting the file will not have the desired effect.

However when I want to pipe using tee should it be:

find . |tee /tmp/output.txt 2>&1   # or
find . 2>&1 |tee /tmp/output.txt   # ?

The latter; it makes sure STDOUT and STDERR of the original command go to the same fd, then feeds them jointly into tee. In the former case, it's the STDERR of the tee command that you'd be joining with its STDOUT.

  • 6
    Interestingly the bash man page says, "If |& is used, the standard error of command1 is connected to command2's standard input through the pipe; it is shorthand for 2>&1 |. This implicit redirection of the standard error is performed after any redirections specified by the command."
    – PP.
    Nov 12 '10 at 10:08
  • 1
    I had to create a small C program that writes both to the stderr and stdout to understand this issue. The redirection > and tee | operators differs when trying to capture both output streams. For redirection I had to ./testapp > /tmp/out.log 2>&1. Whereas for tee I had to ./testapp 2>&1 | tee /tmp/out.log.
    – eigenfield
    Sep 27 '18 at 17:56
  • @daixtr for what it's worth, the | is normally referred to as a pipe operator. tee refers only to the particular program that's being invoked on the far end of the pipe.
    – MadHatter
    Sep 27 '18 at 21:19

It seems a duplicate of https://stackoverflow.com/questions/363223/how-do-i-get-both-stdout-and-stderr-to-go-to-the-terminal-and-a-log-file/65738448#65738448

I will post my answer here too for bash in a script:

exec 1> >(tee x.log) 2> >(tee x.err >&2)

echo "test for log"
echo "test for err" 1>&2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.