BASH / CHAPTER 09
Pipelines, subshells, and failure propagation
AdvancedTrace both data flow and process-local state.
By the end of this chapter
- Predict subshell variable isolation
- Choose an explicit pipeline failure policy
- Recognize command substitution’s text behavior
The idea
A pipeline connects one command’s standard output to the next command’s standard input, but it also creates execution environments whose variable changes may not reach the parent shell. Parentheses explicitly run a list in a subshell. Do not depend on a pipeline loop updating a parent variable without understanding Bash’s execution options; use input redirection when the loop’s state must remain in the current shell.
By default, a pipeline’s status is the status of its final command. With pipefail enabled, a failing earlier command can make the whole pipeline fail; the status is the rightmost nonzero status. This detects more failures but does not undo side effects. Command substitution captures output and removes trailing newlines, so it is suitable for text results only when that transformation matches the contract.
#!/usr/bin/env bash
value=1
( value=9 )
printf '%s\n' "$value"
set -o pipefail
if false | true; then printf 'ok\n'; else printf 'failed\n'; fi1 failed
The subshell assignment does not alter the parent’s value. With pipefail, the earlier false command makes this pipeline unsuccessful despite true finishing last.
Try it yourself
Rewrite a line-counting pipeline so the final count is available in the parent shell.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING