4

The following script runs on Solaris using /bin/ksh and on Linux using /bin/sh

cmd | tee -a  cmd.log | tail
exit $?

The output of cmd is saved in a file cmd.log and the last lines are displayed on stdout.

The purpose of exit $? was to exit the script with the return code of cmd. Of course this

does not work because $? holds the return code of the last command in the pipeline which is

tail.

Workaround (I will omit all cleanup activities) :

{ cmd;  echo $? >  error.file; } | tee -a  cmd.log | tail
exit `cat error.file`

But is there another way to get the returncode of cmd and to avoid the creation of a file like error.file?

1 Answers1

1

Try this:

(cmd; echo $? 1>&2) | tee -a  cmd.log | tail

Or, if you want to redirect STDERR to tee:

exec 3>&1; (cmd 2>&1; echo $? >&3 3>&-)| tee -a  cmd.log; exec 3>&-
dchirikov
  • 3,888