Advanced Bash-Scripting Guide: An in-depth exploration of the art of shell scripting
Prev | Chapter 11. Loops and Branches | Next

# 11.2. Nested Loops

A nested loop is a loop within a loop, an inner loop within the body of an outer one. How this works is that the first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes. Of course, a break within either the inner or outer loop would interrupt this process.

Example 11-20. Nested Loop

       1 #!/bin/bash
       2 # nested-loop.sh: Nested "for" loops.
       3
       4 outer=1             # Set outer loop counter.
       5
       6 # Beginning of outer loop.
       7 for a in 1 2 3 4 5
       8 do
       9   echo "Pass $outer in outer loop."
      10   echo "---------------------"
      11   inner=1           # Reset inner loop counter.
      12
      13   # ===============================================
      14   # Beginning of inner loop.
      15   for b in 1 2 3 4 5
      16   do
      17     echo "Pass $inner in inner loop."
      18     let "inner+=1"  # Increment inner loop counter.
      19   done
      20   # End of inner loop.
      21   # ===============================================
      22
      23   let "outer+=1"    # Increment outer loop counter.
      24   echo              # Space between output blocks in pass of outer loop.
      25 done
      26 # End of outer loop.
      27
      28 exit 0

See Example 27-11 for an illustration of nested while loops, and Example 27-13 to see a while loop nested inside an until loop.

Prev | Home | Next
Loops and Branches | Up | Loop Control