Getting error return code

I need to try and get the error return code from the tar command when being used as follows:

tar tvf tarfile 2>logfile | tee -f outputfile
ErrorStat="$?"

I would like to save the error return code from the tar command in a variable,
howver, the example above it is saving the 'tee' error status.

Is there a way to save the 'tar' error code or maybe a better way to utilize the 'tee' command?

What you are getting here is the return code from the tee command.

Redirect the file using > instead of tee.

(don't know what the -f option of tee does)

Well, my purpose for using tee was that I wanted the output to go to the screen as well as a log file.

mknod output.txt p

cat output.txt | tee log.txt &

tar cvf test.tar comm comm2 file21 > output.txt
RETCODE=$?

sleep 1

echo $RETCODE

rm output.txt

Your output is in log.txt

In more recent versions of bash and ksh you can do this:

set -o pipefail
tar tvf tarfile 2>logfile | tee -f outputfile
ErrorStat="$?"
set +o pipefail

Nice one.

Was using ksh on Solaris, which doesn't have this as I can see, but the bash does.

TMPF=/tmp/tar-rc.$$.$RANDOM
(tar tvf tarfile 2>logfile;echo $? >$TEMF) | tee -f outputfile
ErrorStat="$(<$TMPF)"; rm $TMPF

Thanks for all the response.

The '-o pipefail' is a very nice shell feature I wasn't aware of... good to know.

I think I'm going with binlib's solution, it is pretty clean, simple and should work across the different shell versions.