Interview Prep/Shell Scripting/Troubleshooting: quoting, expansion and tool-input bugs

A loop counts errors, but after the loop the count is always 0.

IntermediateTroubleshootingTroubleshooting: quoting, expansion and tool-input bugs
Answer

Likely causes → The loop is on the right side of a pipe (grep ERROR app.log | while read -r l; do count=$((count+1)); done), so it runs in a subshell and its variables vanish when it ends.

Diagnose → echo "inside: $count" at the end of the loop body shows the right number; after the loop it is 0.

Fix →

count=0
while IFS= read -r _; do count=$((count + 1)); done < <(grep ERROR app.log)

Or shopt -s lastpipe in scripts, or simply count=$(grep -c ERROR app.log || true).

Prevent → Feed loops with redirection or process substitution, not pipes, when they set variables.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Troubleshooting: quoting, expansion and tool-input bugs