Skip to main content
Engineering LibreTexts

13-D.11: Script Loops

  • Page ID
    43212
  • Looping Shell Scripts

    There are a total of three looping statements which can be used in bash programming:

    1. while statement
    2. for statement
    3. until statement

    While Statement

    Here the command is evaluated and based on the result loop will be executed; if command is raised to false then loop will be terminated.

    while command
    do
       Statement to be executed
    done

    Here is an example of a while loop. It looks very similar to most programming language while loops.

    #!/bin/bash
    
    count=1 
    
    # Continue in the loop until the variable 'count' is less than 6
    # -lt is less than operator
    while [ $count -lt 6 ] 
    do
        # Print the values 
        echo $count
        
        # increment the value 
        # this is an odd looking increment of count 
        # it could also be done as: ((++count))
        count=`expr $count + 1` 
    done 
    

    The output of the while loop would be:

    1
    2
    3
    4
    5
    

    For Statement

    The for loop operates 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.

    for var in word1 word2 ...wordn 
    do
        Statement to be executed 
    done
    

    In the following example the variable count is set to the next numerical value from the list (1 2 3 4 5). The echo statement prints the output.

    #!/bin/bash
    
    #Start of for loop 
    for count in 1 2 3 4 5
    do
        # Print the value 
        echo "Loop number $count"
    done 
    

    The output is:

    Loop number 1
    Loop number 2 
    Loop number 3
    Loop number 4
    Loop number 5

    Until Statement

    The until loop is executed as many times as the condition/command evaluates to false. The loop terminates when the condition/command becomes true.

    #!/bin/bash
    
    until command
    do
       Statement to be executed until command is true
    done
    

    The example of an until loop:

    #!/bin/bash
    
    count=1 
    # -gt is greater than operator 
    
    #Iterate the loop until count is greater than 5
    until [ $count -gt 5 ] 
    do
        # Print the values 
        echo $count
        
        # increment the value 
        count=`expr $count + 1` 
    done  
    

    Running this script produces the following output:

    1
    2
    3
    4
    5 

    Adapted from:
    "Looping Statements | Shell Script" by bilal-hungund, Geeks for Geeks is licensed under CC BY-SA 4.0

    • Was this article helpful?