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

rouble picture rouble · Mar 9, 2010 · Viewed 21.6k times · Source

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.

Answer

Martin picture Martin · Mar 10, 2010

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

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