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.
More on Arrays, conditionals and loops
How do you declare, populate and iterate an indexed array?BeginnerWhat is the difference between `"${arr[@]}"` and `"${arr[*]}"`?IntermediateHow do associative arrays work and what are they good for in DevOps scripts?IntermediateHow do you read a command's output into an array correctly?IntermediateWhat is the difference between `[ ]`, `[[ ]]` and `(( ))`?BeginnerWhy does `[ $var = "prod" ]` fail when `var` is empty or contains spaces?Intermediate