0

I am using $PIPESTATUS to print the exit code for each pipe command. I now know that pipes run in parallel but once the exit code is <>0, how do I get the script to exit instead of progressing to the next command? Thanks.

I can't put set -e at the top because once the error is detected, the script exits but $PIPESTATUS isn't displayed because that echo command is after any failed command in the pipeline.

Hua Cha
  • 107
  • 1
  • 9
  • 1
    Are you thinking of `set -o pipefail` maybe? – PesaThe Aug 22 '18 at 22:02
  • 2
    Possible duplicate of [Exit when one process in pipe fails](https://stackoverflow.com/questions/32684119/exit-when-one-process-in-pipe-fails) – Benjamin W. Aug 22 '18 at 22:03
  • So, when I put set -e at the top of my script, echo "${PIPESTATUS[@]}" doesn't return any values. – Hua Cha Aug 22 '18 at 22:14
  • Pipes don't progress from command to command; all commands run in parallel. – chepner Aug 22 '18 at 22:20
  • @chepner I learned this yesterday. I don't want it to exit in the middle of a pipe. But once I capture the exit codes from the entire pipe, and there's an error, I want to exit instead of going to the next line. If I set -e at the top, the script exits before the PIPESTATUS is displayed. – Hua Cha Aug 22 '18 at 22:26
  • Don't use `set -e` -- as I advised yesterday, you should implement your own error handling. – Charles Duffy Aug 22 '18 at 22:43

1 Answers1

3
set -o pipefail

true | false | true || { declare -p PIPESTATUS; exit; }
echo "whoops"

output:

declare -a PIPESTATUS=([0]="0" [1]="1" [2]="0")

From Bash Reference Manual:

pipefail

If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands in the pipeline exit successfully. This option is disabled by default.

PesaThe
  • 7,259
  • 1
  • 19
  • 43