bashloggingoutputexitreturn-code

catch exit code in bash script output to screen and log


I'm trying to combine 2 lines that work separately, but I can't get them to work together. To capture and exit code of 1:

Python script.py > /logfile.log 2>&1
ret=$?
if [ $ret -ne 0 ]; then
     exit $ret
fi

To output the result of the script to the screen and a log file:

Python script.py 2>&1 | tee /logfile.log 

I want to combine these 2 commands so that the script will output to the screen and log file, and will also catch the exit code of 1 to abort the script when it fails. I tried combining them in different ways, but the script either continues running, or nothing is output to the screen. Is it possible to do this?


Solution

  • Use array PIPESTATUS:

    Python script.py 2>&1 | tee /logfile.log
    ret="${PIPESTATUS[0]}"
    if [[ "$ret" -ne "0" ]]; then
      exit "$ret"
    fi
    

    From man bash:

    PIPESTATUS: An array variable (see Arrays below) containing a list of exit status values from the processes in the most- recently-executed foreground pipeline (which may contain only a single command).