Looping Statements | Shell Script

Looping Statements in Shell Scripting: There are total 2 looping statements which can be used in bash programming

  1. while statement
  2. for statement

To alter the flow of loop statements, two commands are used they are,

  1. break
  2. 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
    Syntax

    while 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

Example Programs

Example 1:
Implementing for loop with break statement

filter_none

edit
close

play_arrow

link
brightness_4
code

#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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.



My Personal Notes arrow_drop_up

सर्वशक्तिशाली इकलौता

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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.