The Bash FOR Loop Explained & Simplified

Bash For Loop explained

A loop is used to repeat a set of statements repeatedly. The Bash FOR loop is the most basic type of loop, which is used for iteration. Other than this, there are two more types of loops: the while loop and the do-while loop. Imagine that you want to run a single statement multiple times in your code. What will you do? Will you rewrite it again and again in the code to execute? Of course not, you will use loops instead.

What is Bash?

Bash is a command-line language that was written by Brian Fox. It is used in many Linux distributions including some of the most popular Linux distros like Ubuntu, Fedora, Kali Linux and etc. and used as a default login shell for Linux.

Bash provides a command-line interface (CLI) where a user can type different sets of instructions to execute and perform a task. There is also another way to execute commands from a file called shell script which will be discussed later.

What is Bash FOR Loop?

The FOR loop can be used in the command line to repeat the set of statements several times. It will cause iteration for some statements specified by the programmer. This loop can be handy for a lot of programmers in many ways. They can help to automate different tasks and can go beyond that with complex problems. A person with in-depth knowledge of loops can do wonders with the help of it.

bash version

Bash FOR loop syntax

The FOR loop is one of the most straightforward loops that cause iteration to a set of variables, the general syntax of for loop is given below;

for VARIABLE in 1 2 3 4 5 .. N

Run the below command:

command1

command2

commandN

done

In bash the above syntax will be given as;

#!/bin/bash

for i in 1 2 3 4 5

do

echo "Hy $i"

done

Once you execute the above set of instructions, the results you will get will be something like:

Hy 1

Hy 2

Hy 3

Hy 4

Hy 5

bash for loop

#!/bin/bash – It verifies that the following code is a part of Bash coding. Now let’s break each element that we used in the bash code above. The brief introduction of each element is given below:

  • i– i is something that holds the place of a variable. You can write any other name as well like m/$m.
  • In – The “in” separates both variables and the given input items.
  • 1 2 3 4 5 – These are the input numbers that we are assigning to operate on it.
  • Do – The purpose of “do” is to start the loop execution. In the example above, “N” is used to represent the number of repeated executions for the loop. In the case above, the number is assigned to 5.
  • Echo “Hy $i”– Now this is the actual code or instruction that we want to run repeatedly. Once it completes 5 loops, then the execution will stop automatically.
  • Done – This refers to stopping the loop after execution.

The code can be written in a different format depending upon the version of bash that you are running. If the version you are using is v3.0+, then you can easily short the range by using “..”

Have a look at the following codes now:

#!/bin/bash

for i in {1. .5}

do

echo "Easy $i"

done

Another thing, the later versions (v4.0+) allows you to do is the increment. You can easily specify the starting item, ending item or any number and then the increase you want. Its syntax is given as:

{START. .END. .INCREMENT}

Let’s have a look at the code example:

#!/bin/bash

for i in {0..8..2}

do

echo "Easy $i"

done

In the above code example, we are taking 0 as a starting number, and the ending number given as input is 8 that is followed by the increment of 2. The results after the execution will be something like:

Easy 0

Easy 2

Easy 4

Easy 6

Easy 8

bash for loop incremental

Examples regarding bash for loop

You can perform many operations with the help of a bash FOR loop. One thing that you must keep in mind is that for bash file the extension of the file should be “.sh.” If you do not have a bash file present on your desktop then you can easily create a new one by running the command:

Vim filename.sh

The above command will create a new file, and it will be opened in the vim editor where you can write your code.

bash for loop file

Creating infinite Bash FOR loop

In an infinite loop, the loop will keep executing until or unless you stop it by yourself by pressing Control + C.

#!/bin/bash

for (( ; ; ))

do

echo "Hello There!"

done

In the example above, the string given will be executed again and again until you stop the loop by yourself.

bash for loop infinite

Three expression loop

The three expression loop consists of three expressions that include an initializer expression referred to as EXP1, a condition (EXP2) and a counting expression (EXP3). This loop is also known as the C type loop because of the similarity in the code structure. Have a look at the syntax:

for (( EXP1; EXP2; EXP3 ))

do

command1

command2

command3

done

Three expression loop example in bash for loop:

#!/bin/bash

for (( c=1; c<=5; c++ ))

do

echo "Hy $c"

done

According to the code above, it says that the beginning value is 1. The loop will keep executing until the condition (EXP2) is true, and the ++ sign in the above code displays the increment by 1. The loop will be again repeated by starting from the first value.

The results will be something like this after the execution of the code.

Hy 1

Hy 2

Hy 3

Hy 4

Hy 5

bash for loop expression

Creating Skip and Continue bash FOR loop

The skip and continue loop is used when you want to skip the loop for the specific value and then continue the loop from another value. The syntax is given as:

for I in 1 2 3 4 5

do

if [condition]

then

continue #Go to next iteration of I in the loop and skip statements3

fi

statement

done

We can easily create a skip and continue loop like the following:

for i in {1..5}

do

if [[ "$i" == '4' ]]

then

continue

fi

echo "Hy $i4"

done

The results that you will get after the execution will be something like:

Hy 1

Hy 2

Hy 3

Hy 5

As we can see in the code, the value 4 corresponded with the continue statement that’s why the loop moved onto the 5 value.

bash for loop statement

Creating Conditional Exit with the break loop

The Conditional exit with break loops allows breaking the operation once it meets with the stated condition. Have a look at the syntax:

for I in 1 2 3 4 5

do

if [condition]

then

break

fi

statement

done

Let’s have a look at an example code that conditions exit, and then it breaks the loop:

for city in Karachi Munich NewYork Paris

do

 if [[ "$city" == 'NewYork' ]]; then

   break

 fi

 echo "city: $city"

done

You will get the following output once you executed the code carefully.

city: Karachi

city: Munich

The statement in the above code shows the breaking of the loop once the condition becomes true. After executing the first statement, it will print the string which says ‘Very easy!’.

bash for loop break

Conclusion

The Bash FOR loops shown in the article are very beneficial for automating your daily tasks whether you or in IT or not, these are some simple examples, but there is a lot more than you can do with the help of these loops. You have learned about the basics, now you can move to a more advanced level where you can learn to use bigger loops for more complex tasks.

The one thing you need is to write down the syntax. The introduction to the basics will help you a lot. In this article, we have mostly talked about the Bash For Loop, but there are other loops as well that you need to learn which will be demonstrated in the next article.

Tell us what you think!

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: