Loops are programming constructs that some particular statement needs to be executed repetitively for a finite number of time with respect to the given condition.
Loops that are available in Bourne Shell are
For loop iterates over the set of values for example array until all values are consumed
for name [ [in [words …] ] ; ] do commands; done
for i in `seq 10` do echo "Looping: $i" done
for i in 1 2 3 4 5 6 7 8 9 10 do echo "Looping $i" done
While loop operate on condition where it repeats until condition is false
while test-commands; do consequent-commands; done
INPUT_STR=Bash while [ "$INPUT_STR" != "q" ] do echo "$INPUT_STR is fun" read INPUT_STR echo "You: $INPUT_STR" done
Infinite While Loop
INPUT_STR=Bash while : do echo "$INPUT_STR is fun" read INPUT_STR echo "You: $INPUT_STR" done
Where, while : is always evaluated as true.
Iterates until given condition is evaluated as false which is quite opposite to how while loop works
until test-commands; do consequent-commands; done
INPUT_STR="Bash" until [ "$INPUT_STR" == "q" ] do echo "$INPUT_STR is fun" read INPUT_STR echo "You: $INPUT_STR" done
Loop Control Statements
Loop control flow statements can be used to alter the flow of loops which are also referred as jump statements
If you use break command, it will break or exit the loop unconditionally where as continue will force the loop to go to the next iteration
Following example illustrates the use of continue statement to print only even numbers while iterating sequence from 1 to 10
for i in `seq 10` do if [ $(($i%2)) -ne 0 ]; then continue; fi echo $i done
Following example illustrates the use of break command to exit the loop abruptly with example
for i in `seq 10` do if [ $i -eq 5 ] then break; fi echo $i done echo "Loop is done. Thank you"
Above example prints numbers from 1 to 4 only since we are breaking the loop at number 5.