Nested Loops
A nested loop is a loop placed inside the body of another loop. The outer loop controls the big steps, and for each of its passes the inner loop runs from start to finish. Nested loops are the natural tool whenever your data has two dimensions: rows and columns, folders and the files inside them, servers and the ports on each server, or every pair of items in a list.
Any loop type (for, C-style for, while, until) can be nested inside any other, and the nesting can go as deep as you need, although more than two or three levels quickly becomes hard to read.
Basic Example
for row in 1 2 3; do
for col in A B; do
echo "row=$row col=$col"
done
done
Output:
row=1 col=A
row=1 col=B
row=2 col=A
row=2 col=B
row=3 col=A
row=3 col=B
How It Works
The order of execution is the key idea. When the outer loop sets row to 1, Bash starts the inner loop and lets it finish completely (col takes the value A and then B). Only after that does the outer loop move on to row=2, and the inner loop starts again from its first value. The inner loop therefore runs once for every pass of the outer loop.
The total number of times the innermost body runs is the product of the sizes of the loops. Here it is 3 times 2, which is 6. For two loops of 10 items each it is 100, and for three loops of 10 it is 1000. Remember this multiplication when the lists are large, because the work grows quickly. A pair of loops over 300 items each already means 90,000 passes. Bash handles that, but because it is an interpreted shell, it is far slower than a compiled language, so large nested loops in Bash may take noticeable time.
Counting with C-Style Loops: A Multiplication Table
Nested C-style loops (lesson 79) are the classic way to produce a table:
for (( i = 1; i <= 3; i++ )); do
for (( j = 1; j <= 5; j++ )); do
printf '%4d' $(( i * j ))
done
printf '\n'
done
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
The outer loop picks the row i. The inner loop prints five numbers on the same line, each right-aligned in a field of four characters by %4d (lesson 30). The printf '\n' after the inner loop ends the line, so that the next row starts on a new line. This pattern, with the inner loop building one line and the outer loop ending it, is the basis of every text table or grid you will print from a script.
An Inner Loop That Depends on the Outer One
The limits of the inner loop may use the outer variable. This prints a triangle:
for (( i = 1; i <= 4; i++ )); do
line=""
for (( j = 1; j <= i; j++ )); do line+="*"; done
echo "$line"
done
Output:
*
**
***
****
The inner loop runs i times, so the first line gets one star, the second gets two, and so on. The += operator appends text to a variable (lesson 34). Notice that line is reset to an empty string at the start of every outer pass. This reset step is important, and the next sections show what happens without it.
Use Different Names for Different Loops
Every loop needs its own variable. If you reuse the same name in an inner loop, it overwrites the variable of the outer one:
for i in 1 2 3; do
for i in a b; do echo -n "$i "; done
echo "(outer now $i)"
done
Output:
a b (outer now b)
a b (outer now b)
a b (outer now b)
After the inner loop, the outer i shows b, not 1, 2 or 3. The outer loop still ran three times, because the shell takes the next value from its own list at the start of each pass, but any code in the outer body that used $i after the inner loop saw the wrong value. With distinct names there is no confusion:
for outer in 1 2 3; do
for inner in a b; do echo -n "$outer$inner "; done
echo
done
Output:
1a 1b
2a 2b
3a 3b
Choose names that say what each variable means (row and col, dir and file, server and port). Plain i, j and k are fine for short numeric loops.
Resetting Counters in while Loops
With for loops, the shell takes care of the starting values. With while loops, you create the inner counter, and you must set it again at the start of every outer pass:
i=1
while [ "$i" -le 2 ]; do
j=1
while [ "$j" -le 3 ]; do echo -n "($i,$j) "; j=$((j + 1)); done
echo
i=$((i + 1))
done
Output:
(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
The line j=1 sits inside the outer loop, so each row restarts at 1. If you move it in front of the outer loop, the inner loop works for the first row only:
i=1; j=1
while [ "$i" -le 2 ]; do
while [ "$j" -le 2 ]; do echo -n "($i,$j) "; j=$((j + 1)); done
i=$((i + 1))
done
echo
Output:
(1,1) (1,2)
In the second row, j is still 3 from the first row, so the inner test fails immediately and nothing is printed. The outer loop still counts up and ends normally, so there is no error message, only missing output. Whenever the output of a nested loop has "missing" rows, check where the inner variable is initialized.
Leaving Nested Loops with break and continue
A plain break leaves only the innermost loop (lesson 84). A number lets you leave more. This search looks for the first pair of numbers whose product is 6:
target=6
found=""
for a in 1 2 3 4; do
for b in 1 2 3 4; do
if (( a * b == target )); then found="$a x $b"; break 2; fi
done
done
echo "first pair for $target: $found"
Output:
first pair for 6: 2 x 3
The pair 2 by 3 is the first one that works, and break 2 ends both loops at once. With a plain break, only the inner loop would have stopped, and the outer loop would have continued to a=3 and a=4, possibly overwriting found with a later pair. The variable found is set before the break, so it is available after the loops, since the loops run in the current shell.
The command continue 2 skips to the next pass of the outer loop:
for a in 1 2 3; do
for b in 1 2 3; do
(( b == a )) && continue 2
echo "a=$a b=$b"
done
done
Output:
a=2 b=1
a=3 b=1
a=3 b=2
Whenever b equals a, the inner loop is abandoned and the outer loop goes on to the next a. For a=1, the very first b is 1, so nothing is printed. For a=3, the values 1 and 2 are printed and then b=3 triggers continue 2. This is a way to print all pairs in which the second number is smaller than the first.
Returning from a Function
Another clean way to leave all loops is to put them in a function and use return (lessons 88 to 91). It also gives the caller a status:
search() {
local a b
for a in 1 2 3; do
for b in 1 2 3; do
if (( a + b == 5 )); then echo "$a+$b"; return 0; fi
done
done
return 1
}
search; echo "status $?"
Output:
2+3
status 0
The function prints the first pair that adds to 5 and leaves immediately, with status 0 meaning "found". If nothing is found, it returns 1. The local line keeps a and b from leaking into the rest of the script (lesson 92).
All Pairs Without Repeats
A common task is to look at every pair of items in a list, where red + green and green + red count as the same pair. Start the inner index just after the outer one:
items=(red green blue)
for (( i = 0; i < ${#items[@]}; i++ )); do
for (( j = i + 1; j < ${#items[@]}; j++ )); do
echo "${items[i]} + ${items[j]}"
done
done
Output:
red + green
red + blue
green + blue
The array has three elements (lessons 97 to 101). For i=0 (red), j runs over 1 and 2. For i=1 (green), j runs over 2 only. For i=2 (blue), the inner loop does not run at all, because j would start at 3. Each pair appears exactly once, and no item is paired with itself.
Walking Folders and the Files Inside
Nested loops over folders and their contents come up often in file handling (lesson 82). This one counts the entries in each sub-folder of a small web site:
mkdir -p site/css site/js site/img
touch site/index.html site/css/a.css site/css/b.css site/js/app.js
for dir in site/*/; do
count=0
for f in "$dir"*; do [ -e "$f" ] && count=$((count + 1)); done
echo "${dir%/}: $count file(s)"
done
Output:
site/css: 2 file(s)
site/img: 0 file(s)
site/js: 1 file(s)
The outer pattern site/*/ matches only folders, and the values end with a slash, so "$dir"* is a correct path pattern with the star outside the quotes. For the empty folder img, the inner pattern matches nothing and stays literal, so the -e test is what prevents the loop from counting the pattern as a file.
Rows of Data
The data of a nested loop may be nested text. Here each array element holds one row of numbers, the outer loop goes over the rows, and the inner loop goes over the numbers of one row:
grid=("1 2 3" "4 5 6" "7 8 9")
for row in "${grid[@]}"; do
sum=0
for n in $row; do sum=$((sum + n)); done
echo "row [$row] sum=$sum"
done
Output:
row [1 2 3] sum=6
row [4 5 6] sum=15
row [7 8 9] sum=24
The "${grid[@]}" expansion in quotes gives each row as one word. The inner $row is intentionally unquoted, so that word splitting (lesson 53) cuts the row into its numbers. This is one of the few places where leaving a variable unquoted is the correct choice, and it is only safe because the content is made of plain numbers that cannot contain wildcards.
A nested loop is also a convenient way to find a best value. The variable best is updated whenever a product is larger than the previous best:
best=0
for a in 3 9 4; do for b in 2 8; do (( a * b > best )) && best=$(( a * b )); done; done
echo "largest product: $best"
Output:
largest product: 72
All combinations of a and b are tested, and the winner is 9 times 8. Loops written on a single line, with ; between the parts, are allowed, though several levels are easier to read on separate lines.
Three Levels
The same idea extends to three loops. This prints all the binary numbers of three digits:
for x in 0 1; do for y in 0 1; do for z in 0 1; do echo -n "$x$y$z "; done; done; done; echo
Output:
000 001 010 011 100 101 110 111
The innermost loop changes fastest, like the last digit of a counter. Three levels of two values give 8 combinations. More than three levels is a sign to rethink the approach, for example by moving the inner part into a function (lesson 88).
Two Loops That Read Files
When both loops read from files, give each one its own input with a redirection after its own done:
printf 'g1\ng2\n' > groups.txt
printf 'x\ny\n' > members.txt
while IFS= read -r g; do
while IFS= read -r m; do echo "$g/$m"; done < members.txt
done < groups.txt
Output:
g1/x
g1/y
g2/x
g2/y
The inner loop opens members.txt again at the start of each outer pass, so it reads the whole file every time. This works because each loop has a different input file.
The danger comes when an inner read uses the same input as the outer loop. Without a redirection of its own, it consumes the next line of the outer file:
printf 'A\nB\nC\nD\n' > in.txt
while IFS= read -r outer; do
IFS= read -r inner
echo "outer=$outer inner=$inner"
done < in.txt
Output:
outer=A inner=B
outer=C inner=D
The outer loop only saw lines A and C, because the inner read took B and D. This is the same input-sharing problem explained in lesson 83, and it applies to any command that reads standard input inside such a loop. When the inner part must read from the terminal (for example, to ask the user a question), give the outer loop its own file descriptor:
printf 'p\nq\n' > ask.txt
while IFS= read -r -u 3 item; do
echo "item $item"
done 3< ask.txt
Output:
item p
item q
The outer loop reads from descriptor 3, so any command in the body, including another read, keeps its usual standard input.
Portability
Nested for and while loops with [ ] tests are plain POSIX and run in Dash. The multiplication table and the triangle used the C-style for (( loop and the (( )) command, which Dash does not support. Dash rejects the C-style form with this message:
Syntax error: Bad for loop variable
Rewrite such loops with while and arithmetic expansion for scripts that must run under sh:
#!/bin/sh
i=1
while [ "$i" -le 3 ]; do
j=1
while [ "$j" -le 3 ]; do
printf '%4d' $(( i * j ))
j=$((j + 1))
done
printf '\n'
i=$((i + 1))
done
The $(( )) expansion is part of POSIX, so it works in Dash, and a loop written this way gives the multiplication table in both shells. Arrays, +=, and -u with read are Bash features too (lessons 188 and 189).