Looping Statements | Shell Script
Looping Statements in Shell Scripting: There are total 2 looping statements which can be used in bash programming
- while statement
- for 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.
Syntaxfor var in word1 word2 ...wordn do Statement to be executed 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
Note: Shell scripting is a case-sensitive language, which means proper syntax has to be followed while writing the scripts.
Recommended Posts:
- Conditional Statements | Shell Script
- String Operators | Shell Script
- Implementing Directory Management using Shell Script
- Bash shell script to swap two numbers
- Bash shell script to find sum of digits
- Introduction to Linux Shell and Shell Scripting
- Making your own Linux Shell in C
- Shell India Interview Experience
- Basic Shell Commands in Linux
- Basic Operators in Shell Scripting
- Reverse a String | Shell Programming
- A Shell program To Find The GCD | Linux
- Array Basics in Shell Scripting | Set 1
- Shell India Interview Experience (IT)
- Developing a Linux based shell
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



