Interview Prep/Shell Scripting/Arrays, conditionals and loops

Why are variables set inside `cmd | while read` lost after the loop?

AdvancedConceptArrays, conditionals and loops
Answer

Each part of a pipeline runs in its own subshell, so the while loop's variables die with that subshell.

count=0
grep ERROR app.log | while read -r _; do ((count++)); done
echo "$count"     # 0

count=0
while read -r _; do ((count++)) || true; done < <(grep ERROR app.log)
echo "$count"     # correct

Alternatives: shopt -s lastpipe (runs the last stage in the current shell when job control is off, which is the case in scripts), or just grep -c ERROR app.log.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Arrays, conditionals and loops