Nested Loops
It is possible to put one loop inside another, even to put different kinds of loops within one another. Although there is no real limit to the number of loops that can be nested, the indentation becomes complicated, and it soon gets difficult to keep track of where all of the loops end. Nested loops are useful because you can use the best attributes of any type of loop that you need. Here, the while loop is best suited for running continuously until the user types the word “quit” to exit the loop. Inside the while loop, the for loop is best suited to iterating over a fixed set of items (fruits in the case of the code that follows). Although $myfruit is listed at the end of the loop, on the first iteration it is blank (myfruit="") so the first run lists only three fruits. Subsequent runs include the user’s favorite fruit at the end of the list.
$ cat nest.sh #!/bin/sh myfruit="" while [ "$myfruit" != "quit" ] do for fruit in apples bananas pears $myfruit do echo "I like $fruit" done # end of the for loop read -p "What is your favorite fruit? " myfruit done # end of the while loop echo "Okay, bye!" $ ./nest.sh I like apples I like bananas I like pears What is your favorite fruit? grapes I like apples I like bananas I like pears I like grapes What is your favorite fruit? plums I like apples I like bananas I like pears I like plums What is your favorite fruit? ...
Get Shell Scripting: Expert Recipes for Linux, Bash, and More now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.