C-Style for Loops

Su Suriya Ravichandran Updated 06 Dec 2026
12 min read ·Lesson 79 of 205

The for loop from lesson 78 walks through a list of words. Sometimes there is no list, only a rule: start at 1, stop after 100, add 2 each time. Bash has a second form of for for exactly this situation. Its header looks like the loops in the C programming language, with three arithmetic expressions separated by semicolons, which is why it is called the C-style or arithmetic for loop. It is the natural tool for counting, and it handles limits that come from variables, which brace expansion cannot do.

Syntax

for (( INITIALIZE; CONDITION; UPDATE )); do
    commands
done

The header, written inside double parentheses, has three parts:

  • INITIALIZE runs once, before the first pass. It normally gives the counter its starting value.
  • CONDITION is tested before every pass. The body runs only while the condition is true, which for arithmetic means the result is not zero.
  • UPDATE runs after every pass, and it normally changes the counter.

All three parts are arithmetic expressions, evaluated the same way as the contents of (( )) and $(( )) (lesson 49). They can read and assign variables, use the operators + - * / %, and compare with < <= > >= == !=.

Basic Example

for (( i = 1; i <= 5; i++ )); do
    echo "i=$i"
done
echo "after the loop i=$i"

Output:

i=1
i=2
i=3
i=4
i=5
after the loop i=6

Understanding the Example

The loop follows a fixed cycle:

  1. The initializer i = 1 runs once.
  2. The condition i <= 5 is checked. It is true, so the body runs and prints i=1.
  3. The update i++ adds one to i, which becomes 2.
  4. The condition is checked again, and the cycle repeats.
  5. When i becomes 6, the condition i <= 5 is false. The loop ends without running the body for 6.

The last line prints 6, not 5. The counter was increased after the final pass, and only then did the condition notice that the limit had been passed. The counter is an ordinary shell variable, so it keeps its last value after the loop, as it did in lesson 78.

Inside the double parentheses, the usual shell rules are relaxed. Variable names do not need a dollar sign, and spaces are optional, so the following loop is valid too:

for ((i=0;i<3;i++)); do echo "pass $i"; done

Output:

pass 0
pass 1
pass 2

The spaced version in the first example is easier to read, and it is the style used in this lesson.

Counting Down and Changing the Step

Any update expression can be used. A decrement counts down, += adds a larger step, and *= multiplies:

for (( n = 5; n >= 1; n-- )); do echo -n "$n "; done; echo "liftoff"

for (( i = 0; i <= 10; i += 2 )); do echo -n "$i "; done; echo

for (( i = 1; i < 1000; i *= 10 )); do echo -n "$i "; done; echo

Output:

5 4 3 2 1 liftoff
0 2 4 6 8 10 
1 10 100 

The countdown uses n-- and a condition n >= 1. The second loop steps by two. The third multiplies by ten each time, which produces powers of ten and stops before reaching 1000, because the condition is i < 1000. A step like this cannot be written with a list at all, which is one of the strengths of this form.

Using Variables as Limits

Lesson 78 showed that a variable cannot be the end of a brace range. In an arithmetic loop it can, because variables are expanded when the condition is evaluated:

limit=4
for (( i = 1; i <= limit; i++ )); do echo -n "$i "; done; echo

Output:

1 2 3 4 

The limit can also be a computed value, such as the number of arguments given to the script. Here the arguments are set with set -- so that the example works on its own:

set -- a b c
for (( i = 1; i <= $#; i++ )); do echo "argument $i of $#"; done

Output:

argument 1 of 3
argument 2 of 3
argument 3 of 3

The $# is the special parameter that holds the number of positional parameters (lesson 43). It is written with a dollar sign because it is a special parameter and not a variable name.

Running Totals

Because the body can use arithmetic freely, loops that accumulate a result are short. The command (( sum += i )) performs an assignment inside the body, without needing $(( )):

sum=0
for (( i = 1; i <= 100; i++ )); do (( sum += i )); done
echo "sum 1..100 = $sum"

fact=1
for (( i = 2; i <= 10; i++ )); do (( fact *= i )); done
echo "10! = $fact"

Output:

sum 1..100 = 5050
10! = 3628800

The second loop multiplies the numbers from 2 to 10 together, giving the factorial of 10. Bash integers are 64 bits wide. The factorial of 20 still fits (2432902008176640000), but extending the loop to 21 wraps around to the negative number -4249290049419214848, because the true value is too large and Bash does not report an error (lesson 73 lists these limits).

Several Variables with the Comma Operator

Each part of the header may contain several expressions separated by commas. This lets two counters move at once:

for (( i = 0, j = 10; i < j; i += 3, j -= 3 )); do
    echo "i=$i j=$j"
done

Output:

i=0 j=10
i=3 j=7

On the third check, i is 6 and j is 4, so i < j is false and the loop ends. Both variables were initialized together and both were updated after each pass. Counters that move toward each other like this are useful for tasks such as checking whether a string reads the same in both directions.

Leaving Parts Empty

Every part of the header is optional. The semicolons must stay, but any of the three parts can be empty. An empty initializer means that the counter was prepared earlier, and an empty update means that the body takes care of it:

i=0
for (( ; i < 3; )); do echo "i=$i"; (( i++ )); done

Output:

i=0
i=1
i=2

An empty condition counts as true, so the loop never ends by itself. The shorthand for (( ; ; )) is the traditional infinite loop, and the body must leave it with break (lesson 84):

for (( ; ; )); do
    (( count++ ))
    [ "$count" -ge 3 ] && break
done
echo "count=$count"

Output:

count=3

The unset variable count counts as 0 in arithmetic, and (( count++ )) raises it by one on every pass. When it reaches 3, the test succeeds and break ends the loop. An infinite loop without a reliable exit is a bug, and lesson 87 returns to that topic.

The same rule applies to a missing condition combined with an initializer and an update:

for (( i = 0; ; i++ )); do
    (( i >= 2 )) && break
    echo "i=$i"
done

Output:

i=0
i=1

When the Body Never Runs

The condition is checked before the first pass. If it is already false, the body is skipped completely, and the status of the loop is 0:

for (( i = 10; i < 5; i++ )); do echo never; done
echo "status: $?  i=$i"

Output:

status: 0  i=10

The initializer still ran, so i is 10 afterward, but the update never did.

The Counter After the Loop and Inside It

The counter variable is global. It replaces any earlier value of the same name, and it is not restored after the loop:

i=100
for (( i = 0; i < 3; i++ )); do :; done
echo "i after loop is $i, the earlier value 100 is gone"

Output:

i after loop is 3, the earlier value 100 is gone

The colon : is a command that does nothing, which makes a valid empty body. Inside a function, declare the counter as local (lesson 92) when the name might clash with a variable in the caller.

The body may also change the counter, and the change affects the next condition check:

for (( i = 0; i < 10; i++ )); do
    echo "i=$i"
    (( i += 3 ))
done

Output:

i=0
i=4
i=8

Each pass moved the counter by 3 inside the body and by 1 in the update, so it advanced by 4 per pass. This is allowed, but it makes loops harder to read, so a single place that changes the counter is usually clearer.

The Exit Status of the Loop

As with the list form, the status of a C-style loop is the status of the last command that ran in the body. When that command is an arithmetic test, the status follows the rule that a result of zero means failure:

for (( i = 0; i < 3; i++ )); do (( i == 99 )); done
echo "status after last body command (( i == 99 )): $?"

for (( i = 0; i < 3; i++ )); do true; done
echo "status with true: $?"

Output:

status after last body command (( i == 99 )): 1
status with true: 0

The comparison i == 99 was false on every pass, and (( )) reports status 1 when its result is zero. That status became the status of the whole loop.

Practical Applications

A Multiplication Table

Two loops, one inside the other, produce rows and columns. The outer loop picks the row, and the inner loop prints the cells of that row (lesson 85 covers nested loops in depth):

for (( row = 1; row <= 3; row++ )); do
    for (( col = 1; col <= 4; col++ )); do
        printf '%4d' $(( row * col ))
    done
    printf '\n'
done

Output:

   1   2   3   4
   2   4   6   8
   3   6   9  12

The format %4d prints each number right-aligned in a field four characters wide. The printf '\n' after the inner loop ends the row. The $(( row * col )) expansion turns the product into text for printf.

The Fibonacci Sequence

Each number in the sequence is the sum of the two before it. One arithmetic command can update several variables in order, using commas:

a=0; b=1
for (( i = 0; i < 10; i++ )); do
    printf '%d ' "$a"
    (( next = a + b, a = b, b = next ))
done
echo

Output:

0 1 1 2 3 5 8 13 21 34 

The first assignment computes the sum, the second moves b into a, and the third moves the sum into b. The order matters, because the commas evaluate from left to right.

Walking an Array by Index

An array (lessons 97 to 101) stores several values under one name. A C-style loop visits each position by number:

fruits=(apple banana cherry)
for (( i = 0; i < ${#fruits[@]}; i++ )); do
    echo "$i: ${fruits[i]}"
done

Output:

0: apple
1: banana
2: cherry

The expression ${#fruits[@]} is the number of elements in the array, which makes it a good limit. Inside the brackets of ${fruits[i]}, the index is evaluated as arithmetic, so i needs no dollar sign. When the position numbers are not needed, the list form for item in "${fruits[@]}" is shorter.

Working Through a String Backwards

A counter that moves downward can step through the characters of a string. The expression ${s:i:1} extracts one character at position i, and ${#s} is the length of the string:

s="Bash"
rev=""
for (( i = ${#s} - 1; i >= 0; i-- )); do rev+="${s:i:1}"; done
echo "$rev"

Output:

hsaB

The loop starts at the last position, which is the length minus one, and counts down to position 0. The += operator appends each character to the end of the result variable.

Errors to Recognize

The arithmetic in the header uses integers only. A decimal number in the initializer is a syntax error, and Bash does not start the loop:

for (( x = 0.5; x < 2; x++ )); do :; done

Output:

float_loop.sh: line 2: ((: x = 0.5: syntax error: invalid arithmetic operator (error token is ".5")

When fractions are needed, loop over whole numbers and divide the result with awk or bc (lesson 77).

A related trap involves the strict mode set -e (lesson 119). The command (( n++ )) returns status 1 when n was 0, because the expression evaluates to the old value, 0. Under set -e, a failing standalone command ends the script. The header of a for loop is not such a command, and the loop below ran to the end:

set -e
for (( i = 0; i < 3; i++ )); do
    echo "i=$i"
done
echo "finished; i=$i"
n=0
(( n++ ))
echo "never printed because (( n++ )) returned 1"

Output:

i=0
i=1
i=2
finished; i=3

The script ended with status 1 at the line (( n++ )), so the final echo never ran. Writing (( ++n )) or (( n += 1 )) in a script that uses set -e avoids the problem.

Portability

The arithmetic for loop is a Bash feature, shared with Ksh and Zsh, and it is not part of the POSIX shell language. Dash rejects it:

#!/bin/sh
for (( i = 0; i < 3; i++ )); do echo "$i"; done

Output in Dash:

cstyle_dash.sh: 2: Syntax error: Bad for loop variable

A script that must run under sh can use a while loop with a counter instead (lesson 80), together with i=$((i + 1)), which Dash does support. Lessons 188 and 189 list the other places where Bash syntax and POSIX syntax differ.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about C-Style for Loops and get answers drawn from it.

Signed-in readers only.