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?

5
  • Have you seen this Q & A?
    – Joseph R.
    Oct 16, 2013 at 14:56
  • Looks like set -o pipefail works in bash and ksh.
    – Kevin
    Oct 16, 2013 at 15:17
  • @Kevin: set -o pipefail did not work on Solaris 10, "bad option"
    – miracle173
    Oct 16, 2013 at 15:38
  • @Kevin: I see it is a duplicate now and your link contains the answers
    – miracle173
    Oct 16, 2013 at 15:39
  • @Joseph R. : I see it is a duplicate now and your link contains the answers
    – miracle173
    Oct 16, 2013 at 15:40

1 Answer 1

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>&-
2
  • How should this work? That writes to the logfile and the output.
    – miracle173
    Oct 16, 2013 at 14:19
  • I've updated my answer. You can write echo output to stderr.
    – dchirikov
    Oct 16, 2013 at 15:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.