C-Style for Loops
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:
- The initializer
i = 1runs once. - The condition
i <= 5is checked. It is true, so the body runs and printsi=1. - The update
i++adds one toi, which becomes 2. - The condition is checked again, and the cycle repeats.
- When
ibecomes 6, the conditioni <= 5is 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.