The for loop is a way to execute a block of code repeatedly until a certain condition is met. All programming languages have loops to let the programmers iterate through the code blocks, so Bash is not an exception.
The loops enable us to execute a task for the required number of times. For example, if we need to complete a task of a similar type fifty times, what you go to do? Either write the code fifty times or you may use a loop (for loop or another type) in Bash.
The other types apart from for loop include while loop and until in Bash (covered in their respective tutorials).
In the case of Bash scripting, the for loop iterates through a list of values (numbers, strings etc.) until all values are exhausted.
Structure of Bash for loop
This is how the for loop can be used in the Bash scripting:
for item in List do [code to be executed here] done
where a list can contain numbers, characters, strings, arrays, etc.
The example in the following section shows using various types in the list as using for loops.
An example of for loop with numbers
In the first example, we will iterate through a list of five numbers using a for loop in Bash. See the code and output below:
The code:
for i in 5 10 15 20 30 do echo "Item: $i" done
The out of the above code is:
Item: 5
Item: 10
Item: 15
Item: 20
Item: 30
Iterating through a numeric range example
Similarly, you may iterate through the ranges as using the for loop. The example below shows using three parameters in a range i.e. start, end and increment as follows:
The code:
#The demo of using for loop and range for x in {0..100..10} do echo "Item in range: $x" done
Output:
Item in range: 0
Item in range: 10
Item in range: 20
Item in range: 30
Item in range: 40
Item in range: 50
Item in range: 60
Item in range: 70
Item in range: 80
Item in range: 90
Item in range: 100
How about using variables instead of static values in range with for loop?
You may require using the variables for setting the start and end values in the range as using it with the for loop. However, this simple approach will not work:
S=0 #Start parameter E=100 #End parameter for x in {$S..$E} do echo "$x" done
This code will not produce the result that you might be expecting. So, how to use a variable? See an example below:
S=0 E=100 for ((i=S;i<=E;i=i+10)); do echo $i done
The result:
0
10
20
30
40
50
60
70
80
90
100
An example of using a list of string items
In the following example, I used a list of strings. For that, we have a list called names and it contains four names. This is followed by using a for loop to iterate through this list and using the “echo” for displaying the name in each iteration:
# The Example of for loop with strings for names in Mike Mina Tina Haynes do do echo “The Name is $names” done
The output:
“The Name is Mike”
“The Name is Mina”
“The Name is Tina”
“The Name is Haynes”
How to use break statement with for loop?
The break is one of the flow control statements available in Bash.
The break statement allows exiting the loop to the next line of code outside of the loop. You may use the break statement with the for as well as other loop types.
The break statement is generally used when a certain task is accomplished. For example, you want to attempt deleting a file three times. In each attempt, the code checks whether the file still exists or removed. If the file is deleted in the first attempt then second and third attempts are useless.
So, you may place the break statement when the attempted file is removed.
In the simple example below, we have ten numbers range (0 to 100) with a gap of 10. As the loop reaches 50, we will exit the for loop by using the break statement:
#A demo of for loop with break for x in {0..100..10} do if [[ "$x" == 50 ]]; then echo "XXXXXXXXXXXXXXXXXXXXXXXXXX" echo "The loop breaks at item 50" break fi echo "Item in range: $x" done
The output:
Item in range: 0
Item in range: 10
Item in range: 20
Item in range: 30
Item in range: 40
XXXXXXXXXXXXXXXXXXXXXXXXXX .
The loop breaks at item 50 .
You can see, the loop exited as it reached the value of 50 in the list.
This is because, as for loop is iterated over the range from 0 to 100 with the increment of 10, upon reaching the value 50, it encountered the if the condition that contains the break statement. So, it exited the loop and did not display the remaining numbers from 60 to 100.
The example of continue statement
The continue is also the flow control statement in Bash that enables only omitting the current iteration rather than exiting the loop entirely.
To understand that, consider the above example again. In the code below, I just replaced the break by continue statement and see the output yourself to make things clearer.
The code:
#A demo of for loop with continue for x in {0..100..10} do if [[ "$x" == 50 ]]; then echo "XXXXXXXXXXXXXXXXXXXXXXXXXX" echo "The loop continues at item 50" continue fi echo "Item in range: $x" done
The result:
Item in range: 0
Item in range: 10
Item in range: 20
Item in range: 30
Item in range: 40
XXXXXXXXXXXXXXXXXXXXXXXXXX .
The loop continues at item 50 .
Item in range: 60
Item in range: 70
Item in range: 80
Item in range: 90
Item in range: 100
You can see, number 50 is omitted from displaying as the output while the remaining numbers from 60 to 100 displayed unlike in the case of the break statement.
An example of iterating over array using for loop
In the following example, an array of four items is created. Then I used a for loop to iterate through that array’s items. In each iteration, the current array item is displayed:
#A demo of array/ for loop Names=('Mike' 'Tina' 'Hina' 'Haynes') # declare an array variable #looping the array for n in "${Names[@]}"; do echo "Name: $n" done
The output:
Name: Mike
Name: Tina
Name: Hina
Name: Haynes
Iterating the array by length of array example
This example uses the array length and used it in the for loop to iterate through the array elements as follows:
## An array variable is declared declare -a array=("Oranges" "Apples" "Bananas" "Mangos") # length of the array arraylength=${#array[@]} # Looping for (( x=1; x<${arraylength}+1; x++ )); do echo $x " of " ${arraylength} " : " ${array[$x-1]} done
The result:
1 of 4 : Oranges
2 of 4 : Apples
3 of 4 : Bananas
4 of 4 : Mangos
You can see the array length is used to display the counter as well as in the for loop.