How to use the bash for loop: Syntax and examples

A Bash for loop is a statement in the Bash programming language that allows a code or script to run repeatedly. It enables you to finish repetitive tasks simultaneously, which helps improve system management efficiency. 

A Bash for loop works by assigning items in a list to a variable and executing an operation for each of them. The basic syntax is as follows:

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

In a real-world scenario, a Bash for loop has various implementations, often involving other programming concepts. For example, you can use a Bash for loop to create a three-expression loop, an infinite loop, a start-and-stop sequence, and more. 

Continue reading to learn more about a Bash for loop and its practical usage examples. 

Download comprehensive bash cheat sheet

What is a Bash for loop?

A Bash for loop is a construction that lets you run a set of commands repeatedly on multiple items with a single execution. It is helpful for automating repetitive operations, such as renaming files, in a command-line-based system like a Linux virtual private server (VPS).

The logic behind a Bash for loop is as follows: a set of commands will continue to run in a loop for each item listed in the variable. This loop ends after running the operation for the last item.

Simply put, you can interpret it as for each item assigned to the variable, loop the same set of commands. However, you can incorporate conditional statements to modify how the loop will run.

Let’s explore the syntax of a Bash for loop line by line in the next section to better understand about how it works.

What is the syntax of a Bash for loop?

The Bash for loop executes a set of commands repeatedly, with the loop iterating through a sequence of items or values. The syntax of such an operation 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 Linux command or operation we will repeat n times. Remember, quotation marks turn anything inside it into one variable.
  • done – stops the loop.

The other two common 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

Now that we understand the Bash for loop syntax, let’s explore examples of how the actual script looks in real-life applications.

What are the examples of a Bash for loop?

Here are Bash for loop examples used to perform multiple operations. If you wish to follow along, you’ll have to log into your VPS. If you’re having trouble, read our Putty SSH tutorial to learn more about how to do so.

Meanwhile, if you’re having trouble with bash, 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.

How to use a Bash for loop with a number

Using a Bash for loop with numbers lets you iterate through a range instead of specifying the items individually. To do this, add the range in curly braces separated by double dots.

For example, the following loop will echo all numbers from one to five:

for i in {1..5}
do
  echo "$i"
done

You can also change the increment using the {START..END..INCREMENT} three-expression syntax. Here’s the code example:

for i in {1..10..2}
do
  echo "Number: $i"
done

Important! In some scripts, the increment syntax uses double parentheses instead of curly braces. Regardless, both have the same function.

The loop will operate on the first value of 1, move up by two increments to 3, and so on. Once it reaches the end value of 10, the code will stop. Here’s the output:

The bash for loop with increment output

Note that the range feature is only available in Bash version 3.0 or later, while the increment is supported in Bash 4.0 and newer.

How to use a Bash for loop with array elements

Combining a Bash for loop with an array iterates over elements grouped together and executes a set of commands for each of them. Instead of using a list, incorporating arrays into Bash makes your script more organized and easily readable, especially when you want to use many items.

To use a Bash for loop with an array, declare the array and its items at the beginning. Then, add it to your for-in expression like so:

#Declare an array of items
array=("item1" "item2" "item3" "item4")

#Iterate through the array and apply the operations
for item in "${array[@]}"
do
   command1
   command2
   command3
done

Here’s an example of a Bash for loop with array elements, using fruits as the items:

fruit_array=("apple" "banana" "red cherry" "green grape")

for fruit in "${fruit_array[@]}"
do
   echo "Fruit: $fruit"
done

The bash loop will iterate through items in the array and use the echo command to print them with the Fruit: prefix. This is what the output looks like:

The output of bash for loop with an array

If you add another command, the loop will operate on the same item before moving to the next one. For example, we’ll insert another echo to add a suffix to the item. Here’s the output:

The output of a bash for loop with an array and two operations

How to use a Bash for loop with a shell variable

Combining a Bash for loop with a shell variable enables you to store items that your code will iterate through. It works similarly to an array in that you group multiple elements, but it uses spaces to split the entries.

A Bash for loop with a shell variable uses the following syntax:

#Define the shell variable
variable="a single item"
#Iterate through the variable and apply the operations
for item in $variable
do
   command1
   command2
   command3
done

The shell variable only contains one data element, but the Bash loop automatically iterates through space-separated items, treating them as different entities. Consider this example:

var_numbers="1 2 3 4 5"

for number in $var_numbers
do
   echo "Number: $number"
done

Instead of printing the numbers as a string, the bash loop will print them individually because they are separated by a space. To treat the items as a single entity, enclose the $var_numbers variable in the for-in expression with quotation marks, like the following:

for number in "$var_numbers"
The output of a bash for loop with a single-item variable

You can change the behavior of Bash variables to change the loop output. To learn more about it, check out our bash variables tutorial.

How to use a Bash for loop with strings

Combining a Bash for loop with strings enables you to iterate through text for operations like concatenating, which is typically grouped into a shell variable or array. Using a shell variable is common if your strings are not separated by a space, like the following syntax:

variable="string1 string2 string3"
for item in $variable
do
   command1
   command2
   command3
done

Meanwhile, use a Bash for loop with strings grouped into an array if your string contains whitespace. In addition to allowing the bash loop to read space-separated items, they are easier to iterate over and expand. Here’s the syntax:

array=("First item" "Second item" "Third item" "Fourth item")
for item in "${array[@]}"
do
   command1
   command2
   command3
done

How to use a Bash for loop to create a three-expression loop

Using a Bash for loop to create a three-expression loop uses a structure similar to the C programming language. This structure is comprised of three writing expressions – an initializer (EXP1), a condition (EXP2), and a counting step (EXP3).

The initializer sets the initial script variable, and the condition determines whether or not the loop continues. Meanwhile, the counting step alters the initial value until it meets the specified condition. The syntax of this loop is as follows:

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

For a better understanding, consider the following code example:

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

The code sets the loop’s initial value as 1. The loop will run as long as the condition in EXP2 is true – the code variable shouldn’t be bigger than 5. The counting expression has the ++ sign, which increments the initial value by one each time the loop runs.

The bash script will echo a message “$c” which refers to the loop value, starting from 1 until it reaches the specified condition. The output will be as follows:

The three-expression bash for loop output

How to use a Bash for loop to create an infinite loop

Creating an infinity loop using a Bash for loop lets you execute code indefinitely until you terminate the process manually by pressing Ctrl + C. There are different ways to do so, such as using the while expression:

while true 
do 
   echo "Hello, world!"
   sleep 1
done 

When the condition is true, the command will print the Hello, world! message with a one-second delay. The snippet uses the while true conditional statement to enable the code to always return the successful exit status.

Since the condition remains true, the code will keep looping the echo command to print the message. Another method is to use the three-expression infinite loop:

for (( ; ; ))
do
   echo "Hello, world!"
   sleep 1
done

In the snippet, we set all the expressions to empty. Since there’s no termination condition to meet, the loop will continue until the user stops it.

The infinite bash for loop output

How to use a Bash for loop to create the skip and continue loop

A Bash for loop lets you create a loop that skips a specific value and continues running afterward. This operation uses the following syntax:

for i in 1 2 3 4 5
do
   if [condition]
   then
      #Continue with the next iteration of i and skip the statement
      continue   
   fi
      statement
done

Here’s a skip-and-continue loop code example:

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

In the snippet, we define the items to modify as numbers one to five. We add an if condition, stating that when the variable value equals 4, the loop doesn’t run the code and continues to the next value. It means the loop will operate on 1, 2, 3, and 5, as the output shows:

The skip-continue bash loop output

How to use a Bash for loop to create a conditional exit with break loop

A Bash for loop lets you create a loop that automatically stops when it meets a specific condition. using the for-in construct like this syntax:

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

You can add another command at the end of the code, which will run after the loop ends. Consider the following example:

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

echo 'That’s all!'

The loop script prints all state names specified in the list but stops once the break condition is met, namely when the current value equals Arkansas. Then, it moves to the next instruction to echo the That’s all! message. Here’s what the output looks like:

The output of bash loop with break conditional exit

How to effectively use a Bash script in Hostinger VPS

Using a Bash for loop with your web hosting provider’s features can further simplify your server administration tasks, making it more efficient.

For example, Hostinger VPS plans have a browser terminal built into our hosting custom control panel, hPanel. It lets you run Linux commands and utilities like bash loop directly from your web browser.

We have an AI agent, Kodee, that simplifies VPS management for beginners. For example, you can ask it to generate Bash for loop scripts for various tasks using simple prompts like “Can you generate a Bash for loop that restarts a list of services?” or “Please create a Bash for loop to back up multiple directories.”

To access the tool, log in to hPanel and click on VPS in the top menu. Select the applicable server and navigate to Kodee in the sidebar. To get accurate results, ensure your web development AI prompts are specific and clear.

Check out our AI prompts for VPS management guide to learn more about using Kodee for various tasks.

Important! Due to AI limitations, some answers may be inaccurate or obsolete.

Key takeaways

A Bash for loop is great for automating repetitive tasks, processing data, and managing a UNIX-like system. For example, with a single execution, you can iterate through names to automatically create new users when setting up a new VPS.

As explained, you can perform various assignments with a Bash for loop by combining it with other Bash constructs, like for-in. You can further expand its functionality by incorporating other command-line tools to create an efficient way to complete a task.

Now that you understand the basics of a Bash for loop, it’s time to practice using it in day-to-day tasks. If you use Hostinger VPS, asking Kodee to write or break down Bash for loop scripts makes the learning process more intuitive, helping you familiarize yourself with it more quickly.

For inspiration, consider checking out our Bash script example tutorial to learn more about the real-world application of the programming language for various purposes.

All of the tutorial content on this website is subject to Hostinger's rigorous editorial standards and values.

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.

Author
The Co-author

Aris Sentika

Aris is a Content Writer specializing in Linux and WordPress development. He has a passion for networking, front-end web development, and server administration. By combining his IT and writing experience, Aris creates content that helps people easily understand complex technical topics to start their online journey. Follow him on LinkedIn.