Table of Contents

How To Use Loop In Bash

This post is about Bash loops. There are following types of loops available in Bash.

  1. Bash For Loop
  2. Bash While Loop
  3. Bash Until Loop

How To Use For Loop In Bash

Lets say we want to loop through an array in Bash.

for x in {1..5}
do
    echo $x
done
1
2
3
4
5

How To Loop Over List Of Files In Bash

ls file*
file1  file2  file3  file4

Lets loop through above list of files in Bash.

for f in $(ls file*)
do
    echo $f
done
file1
file2
file3
file4

Remember how we have used $() to list the files.

How To Loop Over List Of Strings In Bash

Lets try it to loop over list of strings.

for x in 'USA' 'UK' 'France'
do
    echo $x
done
USA
UK
France

How about looping over a array of strings.

countries=('USA' 'UK' 'France') 
for x in ${countries[@]}
do
    echo $x
done
USA
UK
France

How To Use Break Statement In Bash Loop

Lets try to break out of loop if country name is 'UK'; We should see only USA and UK as output.

countries=('USA' 'UK' 'France') 
for x in ${countries[@]}
do
    if [[ "$x" == 'UK' ]]; then
        echo $x
        break
    fi
    echo $x
done
USA
UK

How To Use Continue Statement In Bash Loop

Lets continue with same example and use continue statement in our Bash loop.

In the below example. Below code should print only 'UK' and 'France'

countries=('USA' 'UK' 'France') 
for x in ${countries[@]}
do
    if [[ "$x" == 'USA' ]]; then
        continue
    fi
    echo $x
done
UK
France

How To Use Bash Loop For Range Of Numbers

We already saw one way of doing this. We can define any range using {1..n} syntax to do that.

The other way is using Bash's arithmetic evaluation operator. This is similar to loop that we see in C language.

END=4
for ((i=1;i<=END;i++)); do
    echo $i
done
1
2
3
4

We can also use seq keyword to implement range in Bash.

for x in $(seq 1 4);do
    echo $x
done
1
2
3
4

How To Use While Loop In Bash

While loops are used to run statements till the time condition is true.

Ex: Lets say we want to print numbers till 5. One way to do that is.

i=0
while [ $i -lt 6 ];do
    echo $i
    ((i++))
done
0
1
2
3
4
5

As we see above as soon as the i goes above 5, the condition is false and while loop terminates.

How To Use Until Loop In Bash

Until loop is same as While loop In Bash. Only difference is that Until loop executes the code of block till the time condition is false.

Lets try to run the above example using the Until loop. Only difference is that instead of less than -lt we will have to use -gt operator. So as long as the condition is false, until will execute the code.

i=0
until [ $i -gt 5 ];do
    echo $i
    ((i++))
done
0
1
2
3
4
5

Wrap Up!

In this tutorial, I have covered the basics of looping in Bash. I hope you would find it useful.

Related Topics:

How To Run Bash Commands In Python

How To Check If File Or Directory Exists In Bash

What Is List And Arrays In Bash

How To Compare String In Bash

Related Posts

1