Arithmetic for loops
The Bash arithmetic form is for (( initialization; condition; update )); do commands; done. Initialization runs once. Bash evaluates the condition before each iteration; a nonzero arithmetic value permits the body. After each normal iteration it evaluates the update, then tests again. This is different from a command-list condition: the arithmetic expression is evaluated directly. A continue in this loop still proceeds through the update. A missing condition is treated as true, so do not omit it in a beginner counting loop. Use an exclusive upper bound (i < count) for zero-based positions or an inclusive bound (i <= count) for one-based labels. This syntax is Bash-specific rather than portable POSIX sh syntax.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Numbered task labels
Expected stdout:
task-01task-02task-03Initialization is once; the inclusive condition allows label 3.
Zero-based indexes
count=3for (( i=0; i<count; i++ )); do printf '%s\n' "$i"doneprintf 'end=%s\n' "$i"Expected stdout:
012end=3The final update reaches three, which fails the condition.
Count backward by two
Expected stdout:
642The decrement makes the condition eventually false.
Common mistakes
With i=0; i<=3; i++, four iterations occur, not three. For three zero-based positions, use i<3.
Practice
Generate labels task-01 through task-05 using an arithmetic loop and printf %02d. Change the loop to count down 5 through 1 and predict its final counter.
Next: break, continue and nested loops