10.2. Nested Loops

A nested loop is a loop within a loop, an inner loop within the body of an outer one. What happens 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 may interrupt this process.


Example 10-19. Nested Loop

   1 #!/bin/bash
   2 # 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   # Beginning of inner loop.
  14   for b in 1 2 3 4 5
  15   do
  16     echo "Pass $inner in inner loop."
  17     let "inner+=1"  # Increment inner loop counter.
  18   done
  19   # End of inner loop.
  20 
  21   let "outer+=1"    # Increment outer loop counter. 
  22   echo              # Space between output in pass of outer loop.
  23 done               
  24 # End of outer loop.
  25 
  26 exit 0

See Example 26-7 for an illustration of nested "while" loops, and Example 26-9 to see a "while" loop nested inside an "until" loop.