11.2. Nested Loops. Comtrol DeviceMaster Software Development Kit
Reklaam
Reklaam
Advanced Bash-Scripting Guide
#!/bin/bash
END_CONDITION=end until [ "$var1" = "$END_CONDITION" ]
# Tests condition here, at top of loop.
do
echo "Input variable #1 "
echo "($END_CONDITION to exit)"
read var1
echo "variable #1 = $var1"
echo done
# --- #
# As with "for" and "while" loops,
#+ an "until" loop permits C-like test constructs.
LIMIT=10 var=0 until (( var > LIMIT )) do # ^^ ^ ^ ^^ No brackets, no $ prefixing variables.
echo -n "$var "
(( var++ )) done # 0 1 2 3 4 5 6 7 8 9 10 exit 0
How to choose between a for loop or a while loop or until loop? In C, you would typically use a for loop when the number of loop iterations is known beforehand. With Bash, however, the situation is fuzzier. The
Bash for loop is more loosely structured and more flexible than its equivalent in other languages. Therefore, feel free to use whatever type of loop gets the job done in the simplest way.
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
#!/bin/bash
# nested-loop.sh: Nested "for" loops.
outer=1 # Set outer loop counter.
# Beginning of outer loop.
for a in 1 2 3 4 5 do
echo "Pass $outer in outer loop."
echo "---------------------"
Chapter 11. Loops and Branches 152
Laadi alla
Reklaam