Pipelines and PIPESTATUS
A pipeline connects commands with |, usually sending one command’s stdout into the next command’s stdin. Stages can run concurrently and pipe buffers have limited capacity. |& also routes stderr into the pipe; its implicit duplication occurs after explicit redirections on the left command. Normally the foreground pipeline status is the last stage’s status. With set -o pipefail, it is the status of the rightmost failing stage, or 0 if all succeed. PIPESTATUS records individual foreground stages in left-to-right order. Capture it immediately: saved=( "$?" "${PIPESTATUS[@]}" ) saves the aggregate and components in a single assignment before they are replaced. Do not first assign $? and then capture PIPESTATUS in a second command. A leading ! negates the aggregate status, not the component codes. lastpipe can run the final foreground stage in the current shell when job control is inactive (Chapter 9). An expected early consumer exit can cause a producer to fail from SIGPIPE; pipefail is useful but not a substitute for deciding what success means. The saved aggregate and stage codes can differ: after ! false | true with pipefail off, the aggregate is 1 although the last component succeeded. The next simple command can replace PIPESTATUS, even if it is only an assignment.
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.
Transform a stream
printf 'apple\nbanana\n' | grep -F banana | tr 'a-z' 'A-Z'saved=( "$?" "${PIPESTATUS[@]}" )printf 'statuses: %s\n' "${saved[*]}"Expected stdout:
BANANAstatuses: 0 0 0 0The first saved item is the aggregate, followed by three component statuses.
Compare pipefail modes
set +o pipefailfalse | truesaved=( "$?" "${PIPESTATUS[@]}" )printf 'default: %s\n' "${saved[*]}"set -o pipefailfalse | truesaved=( "$?" "${PIPESTATUS[@]}" )printf 'pipefail: %s\n' "${saved[*]}"Expected stdout:
default: 0 1 0pipefail: 1 1 0Individual statuses stay the same; the aggregate changes.
Pipe both output streams
Expected stdout:
datanoteThe two streams from the left group flow through one pipe.
Common mistakes
An extra printf, test, or assignment can overwrite PIPESTATUS. Capture all statuses in the very next command. Avoid assuming that the first failure in time determines pipefail.
Practice
Run three stages returning 3, 5 and 0, with pipefail off and on. Save both aggregate and component statuses in one array and explain the difference.
Next: Subshells and option inheritance