How do you catch error codes in a shell pipe?

Viewed 47563

I currently have a script that does something like

./a | ./b | ./c

I want to modify it so that if any of a, b, or c exit with an error code I print an error message and stop instead of piping bad output forward.

What would be the simplest/cleanest way to do so?

5 Answers

In bash you can use set -e and set -o pipefail at the beginning of your file. A subsequent command ./a | ./b | ./c will fail when any of the three scripts fails. The return code will be the return code of the first failed script.

Note that pipefail isn't available in standard sh.

This answer is in the spirit of the accepted answer, but using shell variables instead of temporary files.

if TMP_A="$(./a)"
then
 if TMP_B="$(echo "TMP_A" | ./b)"
 then
  if TMP_C="$(echo "TMP_B" | ./c)"
  then
   echo "$TMP_C"
  else
   echo "./c failed"
  fi
 else
  echo "./b failed"
 fi
else
 echo "./a failed"
fi
Related