claude-memory/graph/fixes/fix-bash-var-returns-exit-code-1-with-set-e-when-var-is-0-c292af.md
2026-02-26 23:48:24 -06:00

1.4 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
bash
scripting
debugging
fix
set-e
arithmetic
dotfiles
0.6 0.8 2026-02-27T05:47:56.914678+00:00 2026-02-27T05:48:24.648974+00:00
target type direction strength edge_id
5f31ea7f-9b53-427d-b601-ab98dabaa2e3 RELATED_TO incoming 0.8 5f5d8b39-4f75-4099-bcc6-e2aa87ec3d2b

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.