Pitfall Memory peon-notify

Bash Set E Arithmetic Trap

bashset-earithmeticpeon-notify

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 || true to suppress the exit: (( var++ )) || true
  • (( ${#array[@]} == 0 )) is safe only inside an if condition or &&/|| chains

See also definitions/bash-set-e for the full edge-case map.