Loop state and pipeline subshells
An ordinary foreground loop with input redirection executes in the current shell, so assignments survive afterward. In default Bash settings, each pipeline component runs in a subshell environment; a loop on the right of | may update only that environment, not the parent. The pipeline can print correct output while the parent counter remains unchanged. Move the input to a file redirection or use process substitution (done < <(producer)) so the loop itself runs in the current shell. Process substitution executes the producer separately; its failure is not automatically reflected in the loop status. Later pipeline lessons discuss checking producer failures. Bash has shopt -s lastpipe, which lets the final command of a foreground pipeline run in the current shell when job control is inactive. It is not a portable assumption. The examples explicitly disable lastpipe for the default demonstration and use fixed input. In example 2, the && chain runs the counting group only after fixture creation succeeds; the braces group commands in the current shell, not a subshell. A counter alone is not proof that the producer succeeded.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Observe the lost count
shopt -u lastpipecount=0printf '%s\n' a b c | while IFS= read -r line; do count=$(( count + 1 ))doneprintf 'count=%s\n' "$count"Expected stdout:
count=0The loop updates the subshell copy of count.
Keep state with redirection
printf '%s\n' a b c > input.txt && { count=0 while IFS= read -r line; do count=$(( count + 1 )) done < input.txt && printf 'count=%s\n' "$count"}Expected stdout:
count=3The loop runs in the current shell, not a pipeline component.
Keep state with process substitution
count=0while IFS= read -r line; do count=$(( count + 1 ))done < <(printf '%s\n' a b c)printf 'count=%s\n' "$count"Expected stdout:
count=3Only the producer runs separately; the loop keeps its state.
Common mistakes
Do not assume changing a variable inside a piped loop changes the parent. Avoid globally enabling lastpipe just to repair one script; choose an explicit input design.
Practice
Count three fixed lines first with a pipeline and then with a redirected loop. Predict the parent counter for each. Repeat with process substitution and explain why it preserves the count. Use a clean Bash process.
Next: Arrays and structured arguments