diff --git a/graph/fixes/fix-bash-var-returns-exit-code-1-with-set-e-when-var-is-0-c292af.md b/graph/fixes/fix-bash-var-returns-exit-code-1-with-set-e-when-var-is-0-c292af.md new file mode 100644 index 00000000000..876c63e5ca1 --- /dev/null +++ b/graph/fixes/fix-bash-var-returns-exit-code-1-with-set-e-when-var-is-0-c292af.md @@ -0,0 +1,36 @@ +--- +id: c292afbb-9b99-4628-8836-7a8d00c797e5 +type: fix +title: "Fix: Bash ((var++)) returns exit code 1 with set -e when var is 0" +tags: [bash, scripting, debugging, fix, set-e, arithmetic, dotfiles] +importance: 0.6 +confidence: 0.8 +created: "2026-02-27T05:47:56.914678+00:00" +updated: "2026-02-27T05:47:56.914678+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 +```bash +# WRONG (fails when var == 0 with set -e) +((var++)) + +# CORRECT +var=$((var + 1)) +``` + +## Alternative +```bash +# 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.