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
.
Perhaps you could put the exit value from PIPESTATUS into
$?
There is an arcane POSIX way of doing this:
It will set the variable
R
to the return value ofcommand1
, and pipe output ofcommand1
tocommand2
, whose output is redirected to the output of parent shell.Another possibility, with some
bash
flavours, is to turn on thepipefail
option:This having been said, the only way of achieving
PIPESTATUS
functionality portably (e.g. so it'd also work with POSIXsh
) is a bit convoluted, i.e. it requires a temp file to propagate a pipe exit status back to the parent shell process:or, encapsulating for reuse:
or, more generically perhaps:
Use process substitution:
tee runs in a subshell so $? holds the exit status of command.