Loops
Loops are very useful for automating repetitive tasks. when you want to run a series of commands repeatedly until a certain condition is reached.
Type of loops:
- Simple For loop
- Range-based for loop
- C-Styled for loops
- Infinite for loop
Simple For Loop:
for var in word1 word2 … wordN
do
Statement(s) to be executed for every word
done
Example: we want to print number 1 to number 5 in a simple loop.
#!/bin/bash
for i in 1 2 3 4 5
do
echo $i
done
Example: list all of files in home directory.
#!/bin/sh
for FILE in $HOME/ *
do
echo $FILE
done
Range-based for loop:
Instead of writing a list of individual elements, use the range syntax and indicate the first and last element.
Example:
#!/bin/bash
for n in {1..10};
do
echo $n
done
it is also possible to specify an increment when using ranges.
#!/bin/bash
for n in {1..10..2};
do
echo $n
done
C-Styled for loops:
Bash scripts also allow C-style three parameter for loop control expressions.
Example: In below example we want to print number 0 to 10.
#!/bin/bash
for (( i=0; i<=10; i++ ))
do
echo $i
done
while Loop:
Allows you to execute a set of instructions repeatedly until the condition occurs. Usually while loop
Used when we want to manipulate the value of a variable repeatedly.
while command
do
Statement(s) to be executed if command is true
done
Example:
Below example print the number from 0 to 9. In each loop it checked if the value is lower than 10 or not and if the value if lower than 0, it print number and add 1 to the value.
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
Until:
If the result value is incorrect, the provided commands are executed. If the order is correct
A command will not be executed, and the program will jump to the line after executing the command.
Example: Below example prints the number from 1 to 9.
#!/bin/sh
a=0
until [ ! $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done