Search code examples
bashshellerror-handlingpipe

Pipe output and capture exit status in Bash


I want to execute a long running command in Bash, and both capture its exit status, and tee its output.

So I do this:

command | tee out.txt
ST=$?

The problem is that the variable ST captures the exit status of tee and not of command. How can I solve this?

Note that command is long running and redirecting the output to a file to view it later is not a good solution for me.


Solution

  • There is an internal Bash variable called $PIPESTATUS; it’s an array that holds the exit status of each command in your last foreground pipeline of commands.

    <command> | tee out.txt ; test ${PIPESTATUS[0]} -eq 0
    

    Or another alternative which also works with other shells (like zsh) would be to enable pipefail:

    set -o pipefail
    ...
    

    The first option does not work with zsh due to a little bit different syntax.