pipefail and pipeline failures
A pipeline can hide an upstream failure when its last command succeeds. Enable set -o pipefail to make its status reflect the rightmost nonzero component, if any. This does not stop every component immediately and does not undo partial side effects. Capture the overall status and PIPESTATUS in the same assignment before running another command. The array gives statuses in command order, not completion order. If a reader deliberately stops early, an upstream writer can fail with SIGPIPE; classify expected behavior for the particular pipeline rather than declaring every nonzero status a defect. The examples use short fixed producers; no external service is involved. Example 3 intentionally ends with a successful diagnostic after rejection; it does not propagate status 6 to its caller. For an entry point that must fail, explicitly exit with the saved status.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Default and pipefail
set +o pipefailfalse | trueprintf 'default=%s\n' "$?"set -o pipefailfalse | trueprintf 'pipefail=%s\n' "$?" Expected stdout:
default=0pipefail=1The same component outcomes produce different overall statuses.
Capture all statuses
set -o pipefail(exit 3) | (exit 5) | truesaved=( "$?" "${PIPESTATUS[@]}" )printf 'overall=%s\n' "${saved[0]}"printf 'parts=%s\n' "${saved[*]:1}" Expected stdout:
overall=5parts=3 5 0The rightmost nonzero is 5, even though the last command succeeded.
Check a pipeline explicitly
set -o pipefailif printf 'partial\n' | (cat; exit 6); then printf 'accepted\n'else rc=$? printf 'rejected=%s\n' "$rc" >&2fiExpected stdout:
partialExpected stderr:
rejected=6Partial data was already printed. The status check cannot retract it.
Common mistakes
Do not assume pipefail means the first failure by time, or that it cancels later commands. rc=$? followed by reading PIPESTATUS is too late to capture the original array.
Practice
Run three child shells with statuses 3, 5 and 0 in a pipeline. Predict and capture the overall and individual statuses with pipefail on and off.
Next: errexit and its exceptions