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 nestedfor.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 nestedfor.sh ./nestedfor.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
For each value of i the inner loop is cycled through 5 times, with the variable j taking values from 1 to 5. The inner for loop terminates when the value of j exceeds 5, and the outer loop terminates when the value of i exceeds 5.
Chessboard Example
A chessboard is the type of checkerboard used in the game of chess, and consists of 64 squares - eight rows and eight columns arranged in two alternating colors. The colors are called "black" and "white". Let us write a shell script called chessboard.sh to display a chessboard on screen:
#!/bin/bash for (( i = 1; i <= 8; i++ )) ### Outer for loop ### do for (( j = 1 ; j <= 8; j++ )) ### Inner for loop ### do total=$(( $i + $j)) # total tmp=$(( $total % 2)) # modulus # Find out odd and even number and change the color # alternating colors using odd and even number logic if [ $tmp -eq 0 ]; then echo -e -n "\033[47m " else echo -e -n "\033[40m " fi done echo "" #### print the new line ### done
Save and close the file. Run it as follows:
chmod +x chessboard.sh ./chessboard.sh
Sample outputs:
