Understanding Bash For Loop in 2024 With Examples
A for loop is one of the prime statements in various programming languages and helps in managing your VPS platform a lot. Here, we will explain how it is used in the bash programming language – hence the name, “bash for loop.”
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 write a for loop syntax once.
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.
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. Before proceeding, 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.
Bash for Loop to Create a Three-Expression Loop
The three-expression loop uses a structure similar to the C programming language. It 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:
Bash for Loop to Create an Infinity Loop
Bash lets you create an infinity loop that keeps executing code 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 as empty. Since there’s no termination condition to meet, the loop will continue until the user stops it.
Bash for Loop to Create the Skip and Continue Loop
Bash lets you create a loop that skips a specific value and continues running afterward. The code syntax is as follows:
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 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:
Bash for Loop to Create a Conditional Exit With Break Loop
In addition to the three-expression structure, use for-in to automatically stop the loop when the script operation meets a specific condition. Here’s the code 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:
Bash for Loop With Array Elements
Instead of listing the for-in loop items, use an array to make your code more organized and easily readable. It simplifies iterating through data – the process of applying the loop for each item individually.
Declare the array with its item at the beginning and add it to your for-in expression. Here’s the syntax:
#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 loop code with array elements:
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:
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:
Bash for Loop With a Shell Variable
In addition to an array, you can use a shell variable to store an item for bash loops. Here’s the code 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. 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"
Bash for Loop With a Number
When working with numbers in the bash loop, you can use a span instead of specifying the items individually. To do so, add the range in curly braces separated with double dots:
for i in {1..5} do echo "$i" done
In the example, the loop will echo all numbers from one to five. In addition, you can 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 into 3, and so on. Once it reaches the end value of 10, the code will stop. Here’s the 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.
Bash for Loop With Strings
In a bash loop, a shell variable’s common usage is to store multiple strings. It is useful for running tasks in bulk, like renaming files or installing a package. Here’s the syntax:
variable="string1 string2 string3" for item in $variable do command1 command2 command3 done
Alternatively, use arrays if your string contains whitespace. In addition to allowing the bash loop to read space-separated items, they are easier to iterate and expand. Here’s the syntax:
array=("First item" "Second item" "Third item" "Fourth item") for item in "${array[@]}" do command1 command2 command3 done
Effectively Using Bash Script in Hostinger VPS
While using bash for loop helps automate VPS management tasks, it’s also important to leverage your web hosting provider’s features to further improve server administration efficiency.
For example, Hostinger VPS plans have 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 assistant, Kodee, that helps simplify VPS management for beginners. For example, it lets you automatically generate bash for loop scripts for various tasks using simple prompts.
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.
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!
Comments
February 18 2022
Bash version 3.0+ can shorten the range with “. .”. #!/bin/bash for i in {1. .5} is wrong. It needs to be: for i in {1..5}
February 22 2022
Hi! Thanks for letting us know - already fixed in the article :)