- Bash Beginner Series #8: Loops in Bash
- For Loops in Bash
- C-style For Loops in Bash
- List/Range For Loops in Bash
- While Loops in Bash
- Until Loops in Bash
- More on looping in bash scripts
- Print the contents of an array in bash
- Using Break and Continue in bash loops
- Infinite Loops in bash
- BASH for loop examples
- Syntax of for loop:
- Example-1: Reading static values
- Example-2: Reading Array Variable
- Example-3: Reading Command-line arguments
- Example-4: Finding odd and even number using three expressions
- Example-5: Reading file content
- Example-6: Create infinite for loop
- Example-7: Use of for loop with command substitute
- Example-8: Conditional exit with break
- Example-9: Early continuation with continue statement
- Conclusion:
- About the author
- Fahmida Yesmin
Bash Beginner Series #8: Loops in Bash
Loops are essential for any scripting language. Learn for, while and until loops with examples in this chapter of Bash Beginner Series.
Beware of infinite loops!
The ability to loop is a very powerful feature of bash scripting. Loops have a variety of use cases.
In this tutorial, you will explore the three different bash loop structures. You will also learn how to use loops to traverse array elements.
Furthermore, you will learn how to use break and continue statements to control loops, and finally, you will learn how to create infinite loops.
For Loops in Bash
For loops are one of three different types of loop structures that you can use in bash. There are two different styles for writing a for loop.
C-style For Loops in Bash
If you are familiar with a C or C++ like programming language, then you will recognize the following for loop syntax:
for ((initialize ; condition ; increment)); do [COMMANDS] done
Using the aforementioned C-style syntax, the following for loop will print out “Hello Friend” ten times:
[email protected]:~$ bash hello.sh Hello Friend Hello Friend Hello Friend Hello Friend Hello Friend Hello Friend Hello Friend Hello Friend Hello Friend Hello Friend
List/Range For Loops in Bash
Another syntax variation of for loop also exists that is particularly useful if you are working with a list of files (or strings), range of numbers, arrays, output of a command, etc. The list/range syntax for loop takes the following form:
for item in [LIST]; do [COMMANDS] done
For example, the following for loop does exactly the same thing as the C-style for loop you had created in the previous section:
for i in ; do echo "Hello Friend" done
The var.sh script below will output all the files and directory that exists under the /var directory:
#!/bin/bash for i in /var/*; do echo $i done
Below is sample output when you run the var.sh script:
[email protected]:~$ ./var.sh /var/backups /var/cache /var/crash /var/lib /var/local /var/lock /var/log /var/mail /var/metrics /var/opt /var/run /var/snap /var/spool /var/tmp
While Loops in Bash
The while loop is another popular and intuitive loop you can use in bash scripts. The general syntax for a while loop is as follows:
while [ condition ]; do [COMMANDS] done
For example, the following 3×10.sh script uses a while loop that will print the first ten multiples of the number three:
#!/bin/bash num=1 while [ $num -le 10 ]; do echo $(($num * 3)) num=$(($num+1)) done
Here’s the output of the above script:
[email protected]:~$ ./3x10.sh 3 6 9 12 15 18 21 24 27 30
It first initialized the num variable to 1; then, the while loop will run as long as num is less than or equal to 10. Inside the body of the while loop, echo command prints of num multiplied by three and then it increments num by 1.
Until Loops in Bash
If you are coming from a C/C++ background, you might be looking for a do-while loop but that one doesn’t exist in bash.
There is another kind of loop that exists in bash. The until loop follows the same syntax as the while loop:
until [ condition ]; do [COMMANDS] Done
The key difference between until loop and while loop is in the test condition. A while loop will keep running as long as the test condition is true; on the flip side, an until loop will keep running as long as test condition is false!
For example, you can easily create the 3×10.sh script with an until loop instead of a while loop; the trick here is to negate the test condition:
#!/bin/bash num=1 until [ $num -gt 10 ]; do echo $(($num * 3)) num=$(($num+1)) done
Notice that the negation of the test condition [ $num -le 10 ]; is [ $num -gt 10 ];
More on looping in bash scripts
Now that you are familiar with the loops in the bash scripts
Print the contents of an array in bash
If you are following this tutorial series from start, you should be familiar with arrays in bash.
For loops are often the most popular choice when it comes to iterating over array elements.
For example, the following prime.sh script iterates over and prints out each element in the prime array:
#!/bin/bash prime=(2 3 5 7 11 13 17 19 23 29) for i in "$"; do echo $i done
This is the output of the prime.sh script:
[email protected]:~$ ./prime.sh 2 3 5 7 11 13 17 19 23 29
Using Break and Continue in bash loops
Sometimes you may want to exit a loop prematurely or skip a loop iteration. To do this, you can use the break and continue statements.
The break statement terminates the execution of a loop and turn the program control to the next command or instruction following the loop.
For example, the following loop would only print the numbers from one to three:
You can also use a continue statement to skip a loop iteration. The loop continues and moves to the next iteration but the commands after the continue statements are skipped in that partcular iteration.
For example, the following odd.sh script would only print the odd numbers from one to ten as it skips over all even numbers:
Here’s the output that prints odd numbers:
Infinite Loops in bash
An infinite loop is a loop that keeps running forever; this happens when the loop test condition is always true.
In most cases, infinite loops are a product of a human logical error.
For example, someone who may want to create a loop that prints the numbers 1 to 10 in descending order may end up creating the following infinite loop by mistake:
for ((i=10;i>0;i++)); do echo $i done
The problem is that the loop keeps incrementing the variable i by 1. To fix it, you need to change i++ with i— as follows:
for ((i=10;i>0;i--)); do echo $i done
In some cases, you may want to intentionally create infinite loops to wait for an external condition to be met on the system. You can easily create an infinite for loop as follows:
If you want to create an infinite while loop instead, then you can create it as follows:
while [ true ]; do [COMMANDS] done
Awesome! This brings us to the end of this tutorial in the Bash Beginner Series. I hope you have enjoyed making looping around in bash!
Now practice the looping with some simple exercises. You also get the solution in the PDF below.
BASH for loop examples
Loops are used in any programming language to execute the same code repeatedly. Three types of loops are mainly used in programming for doing repetitive tasks. These are for, while, and do-while/repeat-until loop. You can apply for loop on bash script in various ways. Some useful BASH for loop examples has been mentioned in this article.
Syntax of for loop:
# loop through a list
for value in list
do
commands
done
# loop specified values
for value in file1 file2 file3
do
commands
done
# loop through strings resulting from a command
for value in $ ( Linux command )
do
commands
done
# loop through increment or decrement numbers
# traditional procedural for loop
for ( ( i = 0 ; i < 10 ; i++ )
do
commands
done
According to the above syntax, the starting and ending block of for loop is defined by do and done keywords in the bash script. The uses of different loops have shown in the next part of this tutorial.
Example-1: Reading static values
Create a bash file named loop1.sh with the following script to read the values from a list using for loop. In this example, 5 static values are declared in the lists. This loop will iterate 5 times, and each time, it will receive a value from the lists and store it in the variable named color that will print inside the loop.
#!/bin/bash
# Define loop to read string values
for color in Blue Green Pink White Red
do
# Print the string value
echo «Color = $color »
done
The following output will appear after executing the above script.
Example-2: Reading Array Variable
You can use for loop to iterate the values of an array. Create a new bash file named loop2.sh with the following script. In this example, the loop retrieves the values from an array variable named ColorList, and it will print the output only if the Pink value is found in the array elements.
#!/bin/bash
# Declare and array
ColorList = ( «Blue Green Pink White Red» )
# Define loop to iterate the array values
for color in $ColorList
do
# Check the value is pink or not
if [ $color == ‘Pink’ ]
then
echo «My favorite color is $color »
fi
done
The following output will appear after executing the above script.
Example-3: Reading Command-line arguments
Command-line arguments values can be iterated by using for loop in bash. Create a new bash file named loop3.sh with the following script to read and print the command-line argument values using for loop.
#!/bin/bash
# Define loop to read argument values
for myval in $*
do
# Print each argument
echo «Argument: $myval »
done
The following output will appear after executing the above script. Two arguments have been given as command-line arguments here. These are ‘Linux’ and ‘Hint’.
Example-4: Finding odd and even number using three expressions
The C-style syntax of for loop is three expression syntax. The first expression indicates initialization, the second expression indicates termination condition, and the third expression indicates increment or decrement. Create a bash file named loop4.sh with the following script to find out the odd and even numbers from 1 to 5.
# Define for loop in C-style format
for ( ( n = 1 ; n < = 5 ; n++ ) )
do
# Check the number is even or not
if ( ( $n % 2== 0 ) )
then
echo » $n is even»
else
echo » $n is odd»
fi
done
The following output will appear after executing the above script.
Example-5: Reading file content
You can use for loop to read the content of any file by using the ‘cat’ command. Suppose you have a file named ‘weekday.txt‘ which contains the name of all weekdays. Now, create a bash file named loop5.sh to read and print the content of the file.
#!/bin/bash
# Initialize the counter
i = 1
# Define for loop to read the text file
for var in ` cat weekday.txt `
do
# Print the file content
echo «Weekday $i : $var »
( ( i++ ) )
done
The following output will appear after executing the above script.
Example-6: Create infinite for loop
Create a bash named loop6.bash with the following script to know the way to declare infinite for loop. Here, the loop will iterate for infinite times and print the counter value until the user presses Ctrl+C.
#!/bin/bash
# Initialize counter variable
counter = 1
# Display message for termination
echo «Press Ctrl+c to terminate from the loop»
# Define infinite loop
for ( ( ;; ) )
do
# Print the number of iteration
echo «Iterating for $counter time(s).»
# Wait for 1 second
sleep 1
# Increment the counter
( ( counter++ ) )
done
The following output will appear after executing the above script.
Example-7: Use of for loop with command substitute
Create a bash file named loop7.bash with the following script to know the use of for loop to read and print the command output.
#!/bin/bash
echo «All bash files starting with ‘a’ are:»
# Read the output of command substitute using for loop
for val in $ ( ls a * .bash )
do
# Print the file name
echo » $val »
done
The following output will appear after executing the above script.
Example-8: Conditional exit with break
Create a bash file named loop8.bash with the following script to know the way to exit from the loop based on any particular condition.
#!/bin/bash
# Define a for loop to iterate 10 times
for ( ( i = 1 ; i < = 10 ; i++ ) )
do
# Define the conditions to terminate the loop
if ( ( $i % 3== 0 && $i % 6== 0 ) )
then
# Terminate from the loop
echo «Terminated.»
break
else
# Print the current value of i
echo «The current value of i is: $i »
fi
done
The following output will appear after executing the above script.
Example-9: Early continuation with continue statement
Create a bash file named loop8.bash with the following script to know how to omit one or more statement(s) from the loop by using a continuous statement based on the particular condition.
#!/bin/bash
# Declare an associative array
declare -A Applicants
# Intialize the array values
Applicants = ( [ 1022 ] = «Present» [ 1034 ] = «Present» [ 1045 ] = «Absent» [ 1067 ] = «Present» )
echo «List of the applicant’s ID who are present:»
for k in $
do
# Filter the applicant’s ID who are absent
if [ $ == «Absent» ] ; then
continue
else
# Print the applicant’s ID who are present
echo $k
fi
done
The following output will appear after executing the above script.
Conclusion:
Different uses of for loop have been explained in this tutorial by using various examples for helping the bash users to know the purposes of using for loop properly and apply it in their script.
About the author
Fahmida Yesmin
I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.