bash set -o pipefail — catch errors in pipelines
Quick Answer
set -o pipefail
# Now this will fail (grep fails because the file is missing)
cat missing-file.txt | grep "pattern" | wc -l
# Without pipefail: exit code 0 (wc succeeded)
# With pipefail: exit code 1 (cat failed)
Problem without pipefail
Without pipefail, only the exit code of the last command in a pipeline matters:
false | true
echo $? # prints 0 — the "false" failure is silently swallowed
Silent failures in pipelines are a common source of subtle bugs in shell scripts.
Other causes & fixes
Combine with set -e and set -u
#!/usr/bin/env bash
set -euo pipefail
# Script now exits on:
# - any command failure (-e)
# - unset variable reference (-u)
# - pipeline failure (-o pipefail)
Get individual pipeline exit codes
cat file.txt | grep pattern | sort
echo "${PIPESTATUS[@]}" # e.g. "0 1 0" — grep failed, others ok
Allow specific pipeline failures
# Use || true to ignore expected failures
grep "pattern" file.txt | head -5 || true
Related