Search code examples
bashstdoutstderrtee

bash: redirect (and append) stdout and stderr to file and terminal and get proper exit status


To redirect (and append) stdout and stderr to a file, while also displaying it on the terminal, I do this:

command 2>&1 | tee -a file.txt

However, is there another way to do this such that I get an accurate value for the exit status?

That is, if I test $?, I want to see the exit status of command, not the exit status of tee.

I know that I can use ${PIPESTATUS[0]} here instead of $?, but I am looking for another solution that would not involve having to check PIPESTATUS.


Solution

  • Perhaps you could put the exit value from PIPESTATUS into $?

    command 2>&1 | tee -a file.txt ; ( exit ${PIPESTATUS} )