Use Exit Status and Pipefail in Bash Scripts
Observe a failed producer in a successful-looking pipeline, then make the full pipeline report the problem.
Difficulty Beginner
Prerequisites
Use Bash and a fresh working directory that does not contain missing-practice-file. The failure in this example is deliberate. Avoid treating output from the simulated failed run as finished work.
Compare two pipeline results
test ! -e missing-practice-file || exit 1
set +o pipefail
cat missing-practice-file | wc -l
printf 'status without pipefail: %s\n' "$?"
set -o pipefail
cat missing-practice-file | wc -l
printf 'status with pipefail: %s\n' "$?"
The consumer can successfully count zero input lines even when the producer fails. Bash normally uses the last command's status. With pipefail, Bash returns a nonzero status when one stage fails. Read $? immediately after the operation because later commands overwrite it.
Handle failure at the call site
if cat missing-practice-file | wc -l; then
printf '%s\n' 'Pipeline completed.'
else
printf '%s\n' 'Pipeline failed. Review the input.' >&2
fi
Run this second example in the same Bash session with pipefail still enabled. Use stderr for the diagnostic and decide explicitly what the script should do next.
Troubleshooting and practice
In a shell other than Bash, check the local shell documentation before depending on pipefail. A pipeline stage can legitimately stop early, which may make an upstream process report broken pipe. Inspect the commands before treating every nonzero status identically. Create a harmless practice file and repeat with its real name. Confirm that both modes now report success.