← Back to Bash Course | Chapter 4: Loops | Lesson 4 of 14

C-Style for Loop

The C-style for loop gives you explicit control over a counter variable, letting you say exactly how it starts, when to stop, and how it changes each time.

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

bash
#!/bin/bash
for (( i = 0; i < 5; i++ )); do
    echo "i is $i"
done

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

bash
#!/bin/bash
for (( i = 0; i <= 10; i += 2 )); do
    echo "Even number: $i"
done

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

bash
#!/bin/bash
for (( i = 5; i >= 1; i-- )); do
    echo "Countdown: $i"
done
echo "Liftoff!"

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

bash
#!/bin/bash
count=0
for (( ; ; )); do
    echo "count=$count"
    count=$((count + 1))
    if [ "$count" -ge 3 ]; then
        break
    fi
done
Common Mistakes
  1. Forgetting semicolons between the three sections; the syntax strictly requires (( init; condition; update )) with two semicolons, not commas or newlines.
  2. Mixing up which section is which -- the middle section is the *continue* condition (loop keeps running while it's true), not a stop condition.
  3. 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.
Chapter Summary
  • 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 internal break.
  • 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.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.