Signup/Sign In
JANUARY 19, 2022

Bash For Loop in Linux

    BAsh

    Introduction

    Bash loops are convenient. In this portion, we'll look at the numerous loop types available to us and explore when and why you may want to utilize each of them.

    Loops enable us to take a set of instructions and keep re-running them until a particular circumstance is achieved. They help automate repetitive operations.

    There are three fundamental loop structures in Bash scripting which we'll examine in the following. There are also a few statements which we may utilize to regulate the operation of the loop.

    While Loops

    One of the most straightforward loops to deal with is the while loop. They say while an expression is true, keep running these lines of code. They have the following format:

    while [ <some test> ]
    do
    <commands>
    done

    You'll see that similar to if statements, the test is written within square brackets [ ].

    In the example below, we will print the numbers 1 through to 10:

    while loop.sh
    #!/bin/bash
    # Basic while loop
    counter=1
    while [ $counter -le 10 ]
    do
    echo $counter
    ((counter++))
    done
    echo All done

    Let's break it down:

    Line 4: We'll initialize the variable counter with its beginning value.

    Line 5: While the test is accurate (counter is less than or equal to 10), let's run the following instructions.

    Line 7: We may insert whatever commands here we desire. Here echo is being employed since it's a simple approach to demonstrate what is going on.

    Line 8: Using the double brackets, we may raise the counter's value by 1.

    Line 9: We've reached the bottom of the loop, so go back to line 5 and execute the test again. If the test is actual, then run the instructions. If the test is false, then continue executing any instructions after done.

    Until Loops

    The Until loop is pretty similar to the while loop. The distinction is that it will execute the instructions inside it until the test becomes true.

    until [ <some test> ]
    do
    <commands>
    done
    #!/bin/bash
    # Basic until loop
    counter=1
    until [ $counter -gt 10 ]
    do
    echo $counter
    ((counter++))
    done
    echo All done

    As you can see in the sample above, the syntax is nearly precisely the same as the while loop (replace while with until). We can quickly develop a script that accomplishes the same as the example above by altering the test appropriately.

    So you may be wondering, 'Why bother having the two distinct sorts of loops?'. We don't necessarily. The while loop would be able to handle any case. Sometimes, though, it simply makes things a little simpler to read if we express it with till rather than while. Think about the following statement:

    Leave the towel on the line until it's dry.

    We might have said:

    Leave the towel on the line while it is not dry.

    Or:

    Leave the towel on the line while it is moist.

    But they don't appear as beautiful and simple to grasp. So by having both whiles and till we can select whichever one makes the most sense to us and, consequently, end up with code that is simpler for us to comprehend when we read it.

    For Loops

    The for loop is a tiny bit different from the previous two loops. It says for each of the items in a given list, execute the provided set of instructions. It has the following syntax.

    for var in <list>
    do
    <commands>
    done

    The for loop will take each item in the list (in sequence, one after the other), assign that item as the value of the variable var, execute the instructions between doing and done, then go back to the top, retrieve the next thing in the list and repeat over.

    The list is specified as a succession of strings, separated by spaces.

    Here is a basic example to illustrate:

    #!/bin/bash
    # Basic for loop
    names='Stan Kyle Cartman'
    for name in $names
    do
    echo $name
    done
    echo All done

    Let's break it down:

    Line 4: Create an essential list which is a succession of names.

    Line 6: For each of the entries in the list $names, assign the item to the variable $name and conduct the following instructions.

    Line 8: echo the name to the screen to show that the mechanism works. We may have as many commands here as we wish.

    Line 11: echo another command to demonstrate that the bash script resumed running as usual after all the items in the list were processed.

    Ranges

    We may also process a string of numbers.

    #!/bin/bash
    # Basic range in for loop
    for value in {1..5}
    do
    echo $value
    done
    echo All done

    Line 4: It's vital when setting a range like this that there are no spaces present between the curly brackets { }. If there are, it will not be recognized as a range but as a list of things.

    When providing a range, you may give whatever number you desire for the beginning value and ending value. The first figure may be more significant than the second, in which case it will count down.

    It is also possible to provide a value to grow or decrease each time. You accomplish this by adding additional two dots ( .. ) and the importance to step by.

    #!/bin/bash
    # Basic range with steps for loop
    for value in {10..0..2}
    do
    echo $value
    done
    echo All done

    One of the most important uses of loops is processing a series of files. To accomplish this, we may utilize wildcards. Let's imagine we wish to convert a sequence of .html files over to .php files.

    #!/bin/bash
    # Make a php copy of any html files
    for value in $1/*.html
    do
    cp $value $1/$( basename -s .html $value ).php
    done

    Controlling Loops: Break and Continue

    Most of the time, your loops will pass through in a smooth and orderly way. Sometimes though, we may need to interfere and adjust their running somewhat. There are two statements we may issue to achieve this.

    Break

    The break statement instructs Bash to quit the loop immediately away. It may be that there is a common scenario that should cause the coil to finish, but there are also exceptional instances in which it should cease as well. For example, maybe we are copying data, but if the free disk space gets below a specific level, we should stop copying.

    #!/bin/bash
    # Make a backup set of files
    for value in $1/*
    do
    used=$( df $1 | tail -1 | awk '{ print $5 }' | sed 's/%//' )
    if [ $used -gt 90 ]
    then
    echo Low disk space 1>&2
    break
    fi
    cp $value $1/backup/
    done

    Continue

    The continue command instructs Bash to stop running through the current iteration of the loop and begin the next iteration. Sometimes some situations prohibit us from going any farther. For instance, maybe we are using the loop to process a series of files, but if we run across a file for which we don't have the read permission, we should not attempt to process it.

    #!/bin/bash
    # Make a backup set of files
    for value in $1/*
    do
    if [ ! -r $value ]
    then
    echo $value not readable 1>&2
    continue
    fi
    cp $value $1/backup/
    done

    Select

    The chosen mechanism enables you to design a basic menu system. It has the following format:

    select var in <list>
    do
    <commands>
    done

    When called, it will take all the items in the list (similar to other loops, this is a space-separated group of things) and put them on the screen with a number before each item. A popup will be presented, enabling the user to pick a number. When they choose a number and click enter, the matching object will be set to the variable var, and the instructions between doing and done are performed. Once done, a question will be given again so that the user may pick another choice.

    A few items to note:

    • No error checking is done. If the user inputs anything other than a number or a number not relating to an article, then var becomes null (empty) (empty)
    • If the user clicks enter without entering any data, the list of alternatives will be presented again.
    • The loop will finish when an EOF signal is entered, or the break statement is given.
    • You may adjust the system variable PS3 to alter the shown promptly.

    Here is a basic example to explain its usage:

    #!/bin/bash
    # A simple menu system
    names='Kyle Cartman Stan Quit'
    PS3='Select character: '
    select name in $names
    do
    if [ $name == 'Quit' ]
    then
    break
    fi
    echo Hello $name
    done
    echo End

    Let's break it down:

    Line 4: Set up a variable with the list of characters and a final choice which we may pick to exit. Note that a space separates the elements.

    Line 6: Change the value of the system variable PS3 so that the prompt is set to something a bit more meaningful. (By default, it is #?)

    Lines 10 - 13: If the final option, 'Quit,' is picked, break out of the select loop.

    Line 14: Print out a message only to indicate the technique has worked. You may have as many commands here as you want.

    Line 17: Print a message merely to demonstrate that the script has proceeded as usual after the select loop.

    Conclusion

    The Bash for loop is used to repeatedly run a specified collection of commands for a predetermined number of times.

    Adarsh Kumar Singh is a technology writer with a passion for coding and programming. With years of experience in the technical field, he has established a reputation as a knowledgeable and insightful writer on a range of technical topics.
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS