Linux Shell Script Loops

Loops are used for doing repetitive tasks. Like other programming languages, shell scripting supports for and while loops. Suppose you want to print first 100 numbers. You can write 100 echo statements like:

echo 1;
echo 2;
echo 3;
echo 4;
echo 5;
.
.
.
echo 100;

But this seems a huge task for a easy task. We use a loop doing the same task more easily and concisely.

Using for loop

#!/usr/bin 
for (( counter=1; counter<=100; counter++ ))
do
echo "Number: $counter"
done

Here, our loop iterates 100 times. The loop started from the starting point 1, checks the condition if the counter less than or equal to (<=) 100. After every iteration, it increases the counter value by 1 and when the counter becomes 101 then the condition will fail and the loop will break.

We can write the above example like below:

#!/usr/bin 
for counter in {1..100..1}
do
echo "Number: $counter"
done

We can also use a counter which decreases every time:

#!/usr/bin 
for (( counter=5; counter<=1; counter-- ))
do
echo "Number: $counter"
done

Output :

Number: 5
Number: 4
Number: 3
Number: 2
Number: 1

We can increment or decrement the counter value by more than 1. For example, increment by 2:

#!/usr/bin 
for (( counter=1; counter<=10; counter+=2 ))
do
echo "Number: $counter"
done

Output:

Number: 1
Number: 3
Number: 5
Number: 7
Number: 9

The next example is a way of writing a for loop using a list of numbers where we define the starting and ending points of the loop. In the below, the loop starts with number 1 and ends in 3:

#!/bin/bash
for i in 1 2 3
do
   echo "Number is: $i"
done

Output:

Number is: 1
Number is: 2
Number is: 3

Another way of writing this with “..”:

#!/usr/bin/
for i in {1..3}
do
echo "Number is: $i"
done

For loop with an array of elements:

#!/usr/bin/

NAME=('John' 'Wood' 'Rick')
for name in "${NAME[@]}"
do
echo "Name: $name"
done

Output:

Name: John
Name: Wood
Name: Rick

While Loop

Syntax for while loop:

           while [ condition ]
           do
                 statement1
                 statement2
           done

While loop example:

#!/usr/bin/env bash            
                
# While loop example                       
COUNTER=0       
                
while [ $COUNTER -le 5 ]                      
do                      
 echo "COUNT = $COUNTER"       
                
 ((COUNTER++))       
                
done       
                               
echo "while loop completed."       

Output:

COUNT = 0
COUNT = 1
COUNT = 2
COUNT = 3
COUNT = 4
COUNT = 5
while loop completed.

See Spring MVC custom validation. Also see our all the courses and lessons. Do not forget to explore code examples in our GitHub repository.

Follow us on social media

Follow Author