Loops are an essential part of shell scripting. They allow us to repeat a certain block of code until a specific condition is met.
Shell scripting provides us with several types of loops that cater to different needs. In this tutorial, we will explore the different types of loops in shell scripting and how they can be used effectively.
1. For Loop:
The for loop is one of the most commonly used loops in shell scripting. It allows us to iterate over a list of values and perform a set of actions for each value.
Here’s the basic syntax of a for loop:
for variable in list
do
# Code to be executed
done
Let’s say we want to print numbers from 1 to 5 using a for loop:
for num in 1 2 3 4 5
do
echo $num
done
This will output:
- 1
- 2
- 3
- 4
- 5
2. While Loop:
The while loop allows us to execute a block of code as long as a specified condition is true. It is useful when we need to repeat an action until a certain condition is met.
Here’s the basic syntax of a while loop:
while [ condition ]
do
# Code to be executed
done
Let’s write a while loop that prints numbers from 1 to 5:
counter=1
while [ $counter -le 5 ]
do
echo $counter
counter=$((counter+1))
done
3. Until Loop:
The until loop is similar to the while loop, but it executes a block of code until a specified condition becomes true. It is useful when we want to repeat an action until a certain condition is no longer true.
Here’s the basic syntax of an until loop:
until [ condition ]
do
# Code to be executed
done
Let’s write an until loop that prints numbers from 1 to 5:
until [ $counter -gt 5 ]
do
echo $counter
counter=$((counter+1))
done
Difference between While and Until Loops:
The main difference between the while and until loops lies in the condition check. The while loop executes as long as the condition is true, while the until loop executes until the condition becomes true.
Nesting Loops:
In shell scripting, we can also nest loops within each other. This allows us to create more complex and versatile scripts.
Let’s say we want to print all possible combinations of two numbers from 0 to 9:
for i in {0..9}
do
for j in {0.9}
do
echo "$i$j"
done
done
This will output:
- 00
- 01
- 02
- 03
- 04
- 98
- 99
.
In Conclusion:
In this tutorial, we explored the different types of loops available in shell scripting. The for loop is used to iterate over a list of values, the while loop executes a block of code as long as a condition is true, and the until loop executes a block of code until a condition becomes true. By understanding and utilizing these loop constructs, you can create powerful and efficient shell scripts.