When bare ‘tee | command’ won’t suffice

In my 20 years of touching UNIX/Linux, I’d never had a need for this until today. If you search around for common search terms like ‘stdout to screen and file’, you are likely only to get basic information on how to use the UNIX/Linux tee command.

However, command | tee somefile.out loses the exit code of command if you care about checking it.

The bash solution provided by someone on my employer’s internal Linux mailing list is:

{ command; RESULT=$?; } | tee somefile.out

Though I also just learned that one can reference the PIPESTATUS array instead.

command | tee somefile.out
if [ $PIPESTATUS[0] -ne 0 ]; then
    echo "Error..."
fi

1 thought on “When bare ‘tee | command’ won’t suffice”

  1. You can also run `set -o pipefail` and the exit code will bubble up. Extremely useful for scripting, along with `set -o nounset` and `set -o errexit`

Leave a Reply

Your email address will not be published. Required fields are marked *