Skip to content
shellhacks.dev
Bash

Check the Exit Status of Every Pipeline Stage in Bash

Read the exit status of every command in a pipeline from ${PIPESTATUS[@]}. The array is overwritten by the next command, so copy it on the very next line.

1 min read
Summarize in AI

A pipeline reports success, and somewhere in the middle a command failed.

Shell
false | true | false
echo "$? and ${PIPESTATUS[@]}"
false | true | false
echo "first: ${PIPESTATUS[*]}"
echo "second: ${PIPESTATUS[*]}"
false | true
st=("${PIPESTATUS[@]}")
echo "copy: ${st[0]} ${st[1]}"
Text
1 and 1 0 1
first: 1 0 1
second: 0
copy: 1 0

After each foreground pipeline Bash stores the exit status of every stage in the array PIPESTATUS, while $? holds only the status of the last one. The first line shows both. Any command, including echo, replaces the array, which is why the second echo prints a single 0 and the status of the failed stage has to be copied right away. The array is in the Bash manual.

PIPESTATUS is Bash and Zsh specific, where Zsh calls it pipestatus and indexes from 1. In POSIX sh a pipeline gives only the last status, and without a way to ask, set -o pipefail, where available, is the fallback. Expanding the array inside the same command as a subshell, as in $(...), does not see the outer pipeline.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.