Looping Statements in Shell Scripting: There are total 3 looping statements which can be used in bash programming
- while statement
- for statement
- until statement
To alter the flow of loop statements, two commands are used they are,
- break
- continue
Their descriptions and syntax are as follows:
- while statement
Here command is evaluated and based on the result loop will executed, if command raise to false then loop will be terminated
Syntaxwhile command do Statement to be executed done
- for statement
The for loop operate on lists of items. It repeats a set of commands for every item in a list.
Here var is the name of a variable and word1 to wordN are sequences of characters separated by spaces (words). Each time the for loop executes, the value of the variable var is set to the next word in the list of words, word1 to wordN.
Syntax
for var in word1 word2 ...wordn do Statement to be executed done
- until statement
The until loop is executed as many as times the condition/command evaluates to false. The loop terminates when the condition/command becomes true.
Syntaxuntil command do Statement to be executed until command is true done
Example Programs
Example 1:
Implementing for loop with break statement
#Start of for loop for a in 1 2 3 4 5 6 7 8 9 10 do # if a is equal to 5 break the loop if [ $a == 5 ] then break fi # Print the value echo "Iteration no $a" done |
Output
$bash -f main.sh Iteration no 1 Iteration no 2 Iteration no 3 Iteration no 4
Example 2:
Implementing for loop with continue statement
for a in 1 2 3 4 5 6 7 8 9 10 do # if a = 5 then continue the loop and # don't move to line 8 if [ $a == 5 ] then continue fi echo "Iteration no $a" done |
Output
$bash -f main.sh Iteration no 1 Iteration no 2 Iteration no 3 Iteration no 4 Iteration no 6 Iteration no 7 Iteration no 8 Iteration no 9 Iteration no 10
Example 3:
Implementing while loop
a=0 # -lt is less than operator #Iterate the loop until a less than 10 while [ $a -lt 10 ] do # Print the values echo $a # increment the value a=`expr $a + 1` done |
Output:
$bash -f main.sh 0 1 2 3 4 5 6 7 8 9
Example 4:
Implementing until loop
a=0 # -gt is greater than operator #Iterate the loop until a is greater than 10 until [ $a -gt 10 ] do # Print the values echo $a # increment the value a=`expr $a + 1` done |
Output:
$bash -f main.sh 0 1 2 3 4 5 6 7 8 9 10
Note: Shell scripting is a case-sensitive language, which means proper syntax has to be followed while writing the scripts.