Pipeline exit status
- Version
- 5.3
- Since
- 3.0
- Review
- Draft
Summary#
A foreground pipeline normally reports the status of its last command. With set -o pipefail, Bash reports the status of the rightmost failed stage, or zero if all stages succeeded. PIPESTATUS holds the status of each stage in pipeline order.
Syntax#
set -o pipefail
producer | filter | consumer
result=( "$?" "${PIPESTATUS[@]}" )
result[0] holds the overall pipeline status. The next elements hold the individual statuses. Use set +o pipefail to restore the last-command behavior.
Example#
The stages exit with fixed codes. The subshell disables errexit so the example can inspect the deliberately failed pipeline.
(
set +e
set +o pipefail
(exit 3) | (exit 7) | true
result=( "$?" "${PIPESTATUS[@]}" )
printf 'default: %d (stages: %d %d %d)\n' "${result[@]}"
set -o pipefail
(exit 3) | (exit 7) | true
result=( "$?" "${PIPESTATUS[@]}" )
printf 'pipefail: %d (stages: %d %d %d)\n' "${result[@]}"
)
Expected output#
default: 0 (stages: 3 7 0)
pipefail: 7 (stages: 3 7 0)
Common mistakes#
Save both values in one assignment immediately after the pipeline. Even a separate status=$? assignment updates PIPESTATUS and loses the stage results. In a script with set -e, use the pipeline as an if condition when you need to handle a nonzero status. Capture the status in the branch before running other commands.
Version applicability#
Bash 2.0 added PIPESTATUS. Bash 3.0 added pipefail and is the minimum version for the complete example.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0