C-Style for Loop
Basic C-Style for Loop
The three sections -- initialization, condition, update -- are separated by semicolons inside double parentheses, and each is a normal arithmetic expression. The loop runs the body as long as the condition evaluates to non-zero (true).
Example: Basic C-Style for Loop
#!/bin/bash
for (( i = 0; i < 5; i++ )); do
echo "i is $i"
done
Login to try C/C++/Java/PHP code in the editor
Custom Step Sizes
Because the update section is a full arithmetic expression, you can increment by any amount, not just 1 -- for example i += 2 to count by twos, or i-- to count downward. This flexibility is the main advantage over the simpler for...in {1..n} form.
Example: Custom Step Sizes
#!/bin/bash
for (( i = 0; i <= 10; i += 2 )); do
echo "Even number: $i"
done
Login to try C/C++/Java/PHP code in the editor
Counting Down
The C-style loop works just as naturally in reverse by starting from a high value, using a > or >= condition, and decrementing in the update section. This is a common pattern for countdowns or processing something in reverse order.
Example: Counting Down
#!/bin/bash
for (( i = 5; i >= 1; i-- )); do
echo "Countdown: $i"
done
echo "Liftoff!"
Login to try C/C++/Java/PHP code in the editor
Omitting Sections
Any of the three sections can be left empty; leaving all three empty, for (( ; ; )), produces an infinite loop, which is only safe when paired with a break inside the body based on some other condition. This pattern is common when the exit condition is easier to express as a check inside the loop body.
Example: Omitting Sections
#!/bin/bash
count=0
for (( ; ; )); do
echo "count=$count"
count=$((count + 1))
if [ "$count" -ge 3 ]; then
break
fi
done
Login to try C/C++/Java/PHP code in the editor
- Forgetting semicolons between the three sections; the syntax strictly requires
(( init; condition; update ))with two semicolons, not commas or newlines. - Mixing up which section is which -- the middle section is the *continue* condition (loop keeps running while it's true), not a stop condition.
- Trying to use string values or
$prefixes for the counter inside the double parentheses; inside(( ))you write bare variable names and it's implicitly numeric.
- Syntax:
for (( init; condition; update )); do ... done, directly modeled on C's for loop. - All three sections are optional --
for (( ; ; ))alone creates an infinite loop, meant to be paired with an internalbreak. - Inside
(( )), variables are referenced without a leading$, and it fully supports++,--,+=, etc. - This form is ideal when you need a numeric counter with a specific step size (not just 1) or a stop condition based on comparison, not just a fixed list.
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: