Nested Loops

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

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).

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 Nested Loops and get answers drawn from it.

Signed-in readers only.