Shell Script : Nested for loop statement

Shell Script : Nested for loop statement

Nested for loops means loop within loop.

They are useful for when you want to repeat something serveral times for several things.

For example, create a shell script called nestedforloop.sh:

#!/bin/bash
# A shell script to print each number five times.
for (( i = 1; i <= 5; i++ ))      ### Outer for loop ###
do

    for (( j = 1 ; j <= 5; j++ )) ### Inner for loop ###
    do
          echo -n "$i "
    done

  echo "" #### print the new line ###
done

Save and close the file. Run it as follows:

chmod +x nestedforloop.sh
./nestedforloop.sh

Sample outputs:

1 1 1 1 1 
2 2 2 2 2 
3 3 3 3 3 
4 4 4 4 4 
5 5 5 5 5