Bash Set E Arithmetic Trap
What Happened

We wrote ((PASS++)) in peon-health.sh to track passing checks. Under set -euo pipefail, that single expression killed the entire script the moment PASS was zero : because ((0)) evaluates to false (exit code 1), and set -e treats any non-zero exit as a fatal error. The script exited silently. No error message, no hint of what failed.
Root Cause
((expr)) is a test expression in bash, not just an arithmetic statement. When the expression evaluates to 0, bash returns exit code 1 : identical to a failed command. set -e sees that non-zero exit and terminates the script immediately. Post-increment ((var++)) returns the value before incrementing, so on the first call when var=0, it evaluates to 0 and triggers the exit.
This is documented bash behavior, but it surprises everyone the first time. The script doesn’t print anything because set -e exits before the error handling has a chance to run.
How to Avoid
- Use
(( ++var ))(pre-increment) : evaluates to the incremented value, which is always ≥1 - Or use
(( var += 1 )): also always ≥1 - Wrap conditional arithmetic in
if:if (( RANDOM % N == 0 )); then ... - Append
|| trueto suppress the exit:(( var++ )) || true (( ${#array[@]} == 0 ))is safe only inside anifcondition or&&/||chains
See also definitions/bash-set-e for the full edge-case map.
Related
- projects/peon-notify/_index : parent project
- hook-paths-must-be-absolute : companion HOOKS pitfall in the same project
- peon-notify