Loops allow us to take a series of commands and keep re-running them until a particular situation is reached. Loops are useful for automating repetitive tasks.
Here at LinuxAPT, as part of our Server Management Services, we regularly help our Customers to perform related bash scripting queries.
In this context, we shall look into different types of loops and how they are used.
A For loop is used for iterating over a list of objects or items. The list can comprise numbers, strings, characters, or even arrays.
A for loop takes the following structure:
for item in list_of_items
do
command1
command2
done
For example,
1. When looping over a list of strings
Here, we will iterate over a list of strings – in this case, planets – which comprises four items. After iteration, we will print each item on the lost using the echo command:
for planet in Mercury Venus Earth Mars Jupiter
do
echo $planet
done
Then assign execute permissions and run the for_loop.sh bash script. The output displays all the items contained in the list:
$ ./for_loop.sh
Mercury
Venus
Earth
Mars
Jupiter
2. When looping over a range of numbers
With for loops, you can also specify a sequence in a range of numbers by defining the starting point and endpoint using the sequence expression provided:
{START..END}
The example below showcases a for loop that displays numbers from 1 to 10:
for n in {0..10}
do
echo value: $n
done
Once, you run the loop, you will see something like this:
value:0
value:1
value:2
value:3
value:4
value:5
value:6
value:7
value:8
value:9
value:10
Also, you can specify the number of stepwise increments between values using the following sequence expression:
{START..END..STEPWISE_INCREMENT}
For example, the loop below displays numbers from 1 to 10 with a step increase of 2 between the values:
for n in {0..10..2}
do
echo value: $n
done
When you execute the above, the loop will yield:
$ ./for_loop_increment.sh
value:0
value:2
value:4
value:6
value:8
value:10
3. When you loop over an array of elements
Also, you can leverage for loops to iterate over an array of items. For instance, here we have an array called ‘MOVIES’ with different elements which are movie titles:
#!/bin/bash
MOVIES=('Happy Feet' 'Who killed Sara' 'Lupin' 'Money Heist' 'House of cards')
for movie in "${MOVIES[@]}";
do
echo Movie: $movie
done
When the script is executed, the for loop iterates over the entire array and prints out the movie titles.
This article covers different loop formats available in Bash Scripting. Bash For loop is a statement that lets you iterate specific set of statements over series of words in a string, elements in a sequence, or elements in an array.
The syntax of the for loop is:
for VARIABLE in PARAM1 PARAM2 PARAM3
do
// scope of for loop
done