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
- While
- until
For Loop
For loop iterates over the set of values for example array until all values are consumed
Syntax:
for name [ [in [words …] ] ; ] do commands; done
Exmaple
for i in seq 10
do
echo "Looping: $i"
done
Another Example
for i in 1 2 3 4 5 6 7 8 9 10
do
echo "Looping $i"
done
While Loop
While loop operate on condition where it repeats until condition is false
Syntax:
while test-commands; do consequent-commands; done
Example:
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.
Until Loop
Iterates until given condition is evaluated as false which is quite opposite to how while loop works
Syntax:
until test-commands; do consequent-commands; done
Example:
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
- Break
- Continue
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.
Leave a Reply