VPS

Bash For Loop Guide and Examples

A for loop is one of the prime statements in various programming languages. Here, we will explain how it is used in the bash programming language – hence the name, “bash for loop.” Get ready to add a new tool into your developer arsenal!

A for loop is an iteration statement, meaning you can execute code repeatedly. Let’s say you want to run an instruction 5 times. Instead of writing five separate codes, you can just write a for loop syntax once. Let’s explore deeper, shall we?

Bash For Loop Syntax

Basically, the simplest for loop syntax repeats the occurrence of a set of a variable. The syntax typically looks like this:

for VARIABLE in 1 2 3 4 5 .. N
Perform the below command:
    command1
    command2
    commandN
done

In the real world, this syntax would look like the example below:

#!/bin/bash
for i in 1 2 3 4 5
do
 echo "Hello $i"
done

Executing the bash file will cause the following text:

Hello 1
Hello 2
Hello 3
Hello 4 
Hello 5

Let’s inspect each element:

  • #!/bin/bash – shows that the code is a bash script
  • i – is a placeholder for a variable. Meanwhile, $i is the individual value of the variable. You can also write it as c/$c or by any other name
  • in – separates the variable and the items that follow
  • 1 2 3 4 5 –  is an example of items you want to perform the instruction on
  • do – is the keyword that starts the loops. It will then execute the instruction n times, with n being the total number of items. Here, the value of n is 5
  • echo “Hello: $i” – is the code which we will repeat n times. Remember quotation marks turn anything inside it into one variable.
  • done – stops the loop

You can write the code differently depending on the version of bash you’re running:

Bash version 3.0+ can shorten the range with “. .”.

#!/bin/bash
for i in {1. .5}
do
  echo "Hai $i"
done

Bash version 4.0+ allows you to use the {START. .END. .INCREMENT} syntax.

#!/bin/bash
for i in {0. .8. .2}
do
  echo "Hai $i"
done

The result will look like this:

Hai 0
Hai 2
Hai 4
Hai 6 
Hai 8

The other common to syntaxes are:

for VARIABLE in file1 file2 file3
do
    command1 on $VARIABLE
    command2
    commandN
done

Or like this:

for OUTPUT in $(Linux-Or-Unix-Command-Here)
do
    command1 on $OUTPUT
    command2 on $OUTPUT
    commandN
done

Bash For Loop Examples

You can update the syntax to perform multiple operations. Remember, before doing anything you’ll have to log into your VPS server. If you’re having trouble, this tutorial will set you on the right path. Meanwhile, if you’re having trouble with bash, you should check out our guide to the basic bash function. Remember, that bash functions need to be in a .sh file. To create one, run the following in the command line:

vim NameOfFile.sh

This will create a .sh file, and will open it in the VIM editor. You can learn more in the previously mentioned basic bash function article.

Using Bash For Loop to Create an Infinity Loop

Once activated, this loop will keep executing the code until you stop it by pressing Control + C. In this case, the term “Hello World” will keep on reappearing by itself.

#!/bin/bash
for (( ; ; ))
do
  echo "Hello World!"
done

Using Bash For Loop to Create a Three-Expression Loop

The loop is comprised of three writing expressions – an initializer (EXP1), a condition (EXP2), and a counting expression (EXP3). Sometimes people name it the C-style loop because of the close resemblance in code structure. The syntax of this loop is as follows:

for (( EXP1; EXP2; EXP3 ))
do
    command1
    command2
    command3
done

Here’s an example you can try yourself:

#!/bin/bash
for (( c=1; c<=5; c++ ))
do  
  echo "Hai $c"
done

The code says that the initial value is 1.  The loop will be executed, as long as the condition in EXP2 is true, which means it should not be bigger than 5. In addition, the ++ sign shows that the increment is 1. It will then repeat the loop one by one starting from the initial value. Result:

Hai 1
Hai 2
Hai 3
Hai 4 
Hai 5

Using Bash for Loop to Create The Skip and Continue Loop

The continue statement skips the loop for the stated value and continues the loop afterward. Here’s how the syntax would look:

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

By following the syntax we can create a bash skip and continue loop like this one:

for i in {1..5}
do
  if [[ "$i" == '4' ]]
  then
    continue
  fi
  echo "Hai $i4"
done

The output would be:

Hai 1
Hai 2
Hai 3
Hai 5

Since the value 4 matched the continue statement, the loop didn’t perform the code and moved on to the next value, which is 5.

Using Bash for Loop to Create a Conditional Exit with Break Loop

The loop allows you to stop the operation if it meets the stated condition. This can be followed by another instruction. Here’s the syntax:

for I in 1 2 3 4 5
  do
  if [condition]
  then
    break
  fi
  statement
done

When using this function, our code would look like this:

for city in Manila Bangkok Jakarta Kuala Lumpur
do
  if [[ "$city" == 'Jakarta' ]]; then
    break
  fi
  echo "city: $city"
done

echo 'Yes, that’s all!'

And lastly the output:

city: Manila
city: Bangkok
Yes, that’s all!

The statement tells the loop to break the operation once the condition is true (finding the term Jakarta). It will then execute the second code, which is printing a text which says Yes, that’s all.

Summary

Bash for loop is great for automating repetitive tasks. Apart from the basic examples above, you can do a lot more. For instance, you can track files and perform many other tasks. The list goes on!

All you need to do is write the syntax. It might have a steep learning curve, but, reading through this introduction is a good start. Practice always makes perfect! Good luck!

About the author

Edward S.

Edward is Hostinger's copywriter. He's an expert communicator with years of experience in IT as a writer, marketer, and Linux enthusiast. IT is a core pillar of his life, personal and professional. Edward's goal is to encourage millions to achieve an impactful online presence. He also really loves dogs, guitars, and everything related to space.

Add Comment

Click here to post a comment

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

Get Exclusive Content

Join thousands of webmasters who get our free newsletter with tips on how to drive more traffic and revenue to their websites!

Please wait...

Thank you for sign up!

More in VPS
How to Configure a Firewall on Ubuntu 18.04 with UFW
Close