Equivalents of tee command to find exit status of command

Hi,

Want to log the output of command & check the exit status to find whether it succeeded or failed.

> ls abc
ls: abc: No such file or directory
> echo $?
1

> ls abc 2>&1 | tee log
ls: abc: No such file or directory
> echo $?
0

Tee commands changes my exit status to be always successful as tee was successful. :wall:

Kindly let me know the options via which I can obtain the exit status of command while having the output stream flowing on the terminal.

Thanks in advance.

try this... not tested...

ls abc 2>&1 | tee log &&  echo  $? || echo $?

Getting success, return code of 0

ls abc 2>&1 | tee log && echo $? || echo $?
ls: abc: No such file or directory
0

ls abc 2>&1 > log 
echo  $?

That won't give me the output on terminal.
I can later cat or tail it, but it won't be simultaneous.

I want to monitor the progress on my terminal & log the output for later reference.

This is a bit of a kludge, using a temporary file to hold the exit status, but it works:

(ls abc 2>&1; echo $? > tmpfile.$$) | tee log; cat tmpfile.$$; rm -f tmpfile.$$

Another option:

$ ls abc 2>&1 | tee log
ls: abc: No such file or directory
$ echo $?
0

$ set -o pipefail
$ ls abc 2>&1 | tee log
ls: abc: No such file or directory
$ echo $?
1

1 Like

Thanks scottn
set -o pipefail works like a charm.

@DoxieLvr
Tee will have to wait for the list to finish which can add delays in case of big commands.