1.6 KiB
1.6 KiB
| id | type | title | tags | importance | confidence | created | updated | relations | |||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| c292afbb-9b99-4628-8836-7a8d00c797e5 | fix | Fix: Bash ((var++)) returns exit code 1 with set -e when var is 0 |
|
0.6 | 0.8 | 2026-02-27T05:47:56.914678+00:00 | 2026-02-27T05:48:38.596981+00:00 |
|
Bash Arithmetic Pitfall: ((var++)) with set -e
Problem
In bash scripts using set -e (errexit), the expression ((var++)) exits with code 1 when var is 0, because the arithmetic expression evaluates to 0 (falsy) before the increment takes effect. This causes the script to terminate unexpectedly.
Root Cause
(( expr )) uses the arithmetic evaluation exit code: exits 0 if the result is non-zero (truthy), exits 1 if the result is zero (falsy). When var=0, ((var++)) evaluates the current value (0) first, returns exit 1, then increments — but set -e already killed the script.
Fix
# WRONG (fails when var == 0 with set -e)
((var++))
# CORRECT
var=$((var + 1))
Alternative
# Also acceptable
((var += 1)) || true # suppress exit code, but less readable
Context
Discovered while writing dotfiles install.sh/uninstall.sh scripts that used counters initialised to 0.