November 26, 2026 路 #71
The counter that stayed at zero
The script reports 0 failed hosts even though the log clearly contains failures. Which line causes the wrong count?
#!/usr/bin/env bash
set -euo pipefail
failed=0
grep 'status=FAIL' deploy.log | while read -r line; do
failed=$((failed + 1))
done
echo "failed hosts: ${failed}"Next puzzle in UTC
One try. The first answer sticks.
How to fix it
Each side of a pipe runs in its own subshell in bash. The loop increments its own copy of failed, and the parent shell still has 0. Feed the loop with < <(grep ...) instead.
In bash, every command in a pipeline runs in a subshell by default. The while loop after the | increments failed in a child process, and when that process exits the change is gone. The parent shell then prints the original value, 0, with no error, which makes this a quiet bug in CI scripts that count, collect, or sum things.
Fix
Keep the loop in the current shell by using process substitution (or a here-string or temp file):
failed=0
while read -r line; do
failed=$((failed + 1))
done < <(grep 'status=FAIL' deploy.log || true)
echo "failed hosts: ${failed}"
The || true stops grep from failing the script when there are no matches, since it exits 1 on no match. If you must keep the pipe, shopt -s lastpipe runs the last pipeline element in the current shell, but only when job control is off, which is the case in scripts and not in interactive shells. Or skip the loop entirely: failed=$(grep -c 'status=FAIL' deploy.log || true).