Bash error: "let: division by 0"
Fix Bash "let: expression: division by 0" errors, including confusing cases from ++ post-increment and arithmetic typos. Copy-paste fix.
Error String
bash: let: i++: division by 0 (error token is "0")
Tldr
Bash's let and $(( )) arithmetic evaluate expressions using integer math, so any division or modulo by zero — including accidental ones from typos like a stray / where you meant a different operator — aborts with this error. Guard the divisor or fix the expression, and remember `let x++` returns a false exit status when x was 0 before incrementing, which trips set -e.
Cause
Arithmetic contexts (let, $(( )), (( ))) in Bash perform C-style integer arithmetic and raise "division by 0" for any / or % with a zero right-hand side. A related and very common gotcha is unrelated: `let "i++"` evaluates to the pre-increment value as its exit status, so `let "i++"` when i is 0 returns exit status 1 (failure), which under set -e kills the script even though no division happened — easy to misdiagnose as this error.
Repro
#!/usr/bin/env bash
set -e
total=0
count=0
average=$((total / count)) # bash: division by 0Fix
#!/usr/bin/env bash
set -euo pipefail
total=0
count=0
# Guard against zero before dividing
if (( count == 0 )); then
average=0
else
average=$((total / count))
fi
# For the let ++ / set -e gotcha, use (( )) with || true, or ((i++)) ||:
i=0
((i++)) || true # does not abort the script even though i started at 0Explanation
Always validate a divisor is non-zero before using it in $(( )) or let, especially when it comes from user input, a loop counter, or a count of matched items that could legitimately be zero. Separately, remember that (( expr )) and let return the arithmetic truthiness of the *result* as their exit status, which combined with set -e can end scripts unexpectedly on expressions like `((count--))` when count starts at 1.
Related Shellcheck
SC2004
Faq
Q
Why does `((i++))` sometimes kill my script under set -e?
A
Post-increment `((i++))` evaluates to i's value *before* incrementing. If i is 0, the expression evaluates to 0 (false), so `(( ))` returns a non-zero exit status and set -e aborts the script, even though nothing actually failed.
Q
How do I safely increment a counter under set -e?
A
Use `((i++)) || true`, `: $((i++))`, or pre-increment style `((++i))`, which evaluates to the new value and is truthy as soon as i reaches 1 or higher.
Q
Does Bash support floating point in $(( ))?
A
No. Bash arithmetic is integer-only; dividing 5/2 gives 2, not 2.5. Use `bc -l` or `awk` for floating-point math, and be aware that integer division by zero always errors while division producing a fractional truncated result does not.