Bash For Loop Guide and Examples

A for loop is one of the prime statements in various programming languages and helps in managing your VPS a lot. 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?

Download Comprehensive Bash Cheat Sheet

Bash For Loop Syntax

Basically, the simplest for loop syntax repeats the occurrence of a set of a variable. The bash sequence 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 sequence:

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 "House $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 "Hello $i"
done

The result of this bash sequence will look like this:

Hello 0
Hello 2
Hello 4
Hello 6 
Hello 8

The other common two loop command syntaxes are this:

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

And 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. If you’re having trouble, this Putty SSH tutorial will set you on the right path. Meanwhile, if you’re having trouble with bash, you should check out our bash scripting tutorial. Remember, that bash functions need to be in a .sh file. To create one, run the following in the command line:

vim filename.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 loop command you can try yourself:

#!/bin/bash
for (( c=1; c<=5; c++ ))
do  
  echo "Hello $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:

Hello 1
Hello 2
Hello 3
Hello 4 
Hello 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   #Continue with the next iteration of I and skip statement 3
 fi
 statement
done

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

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

The output for this bash sequence would be:

Hello 1
Hello 2
Hello 3
Hello 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 loop command would look like this:

for city in Alabama Alaska Arizona Arkansas California
do
  if [[ "$state" == 'Arkansas' ]]; then
    break
  fi
  echo "state: $state"
done

echo 'That’s all!'

And the output:

state: Alabama
state: Alaska
state: Arizona
That’s all!

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

Conclusion

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 loop commands. It might be a learning curve, but, reading through this introduction is a good start. Practice always makes perfect! Good luck!

Looking for more bash guides?

Beginner’s Guide to Bash Array

Author
The author

Edward S.

Edward is a content editor with years of experience in IT writing, marketing, and Linux system administration. His goal is to encourage readers to establish an impactful online presence. He also really loves dogs, guitars, and everything related to space.