Loops are fundamental structures in shell scripting that allow repetitive execution of commands or blocks of code until a condition is met or for a specified number of times.
Utilizing loops makes scripts efficient, reduces code duplication, and automates repetitive tasks in Linux environments.
Understanding different types of loops, their syntax, and control mechanisms is essential for writing effective and flexible shell scripts.
Types of Loops in Shell Scripting
Linux shell scripting mainly supports three types of loops:
For Loop
The for loop iterates through a list of items or a sequence, executing the commands for each iteration.
Syntax:
for var in list
do
commands
doneExample:
for i in 1 2 3 4 5
do
echo "Iteration $i"
doneIt can also iterate over a range using brace expansion:
for i in {1..5}
do
echo "Number $i"
doneWhile Loop
The while loop executes as long as its condition stays true.
Syntax:
while [ condition ]
do
commands
doneExample:
count=1
while [ $count -le 5 ]
do
echo "Count: $count"
((count++))
doneUntil Loop
The until loop runs until the specified condition becomes true.
Syntax:
until [ condition ]
do
commands
doneExample:
count=1
until [ $count -gt 5 ]
do
echo "Count: $count"
((count++))
doneLoop Control Statements
Below are important loop control mechanisms. They make scripts more flexible and responsive to conditions.
1. break: Exits loop immediately.
2. continue: Skips the rest of the current iteration and moves to the next.
Example:
for i in {1..10}
do
if [ $i -eq 5 ]; then
echo "Encountered 5, breaking loop."
break
elif [ $i -eq 3 ]; then
echo "Skipping 3"
continue
else
echo "Current number: $i"
fi
doneNested Loops
Loops can be nested within each other to iterate over multiple dimensions.
Example:
for i in 1 2 3
do
for j in a b
do
echo "Outer loop: $i, Inner loop: $j"
done
done
We have a sales campaign on our promoted courses and products. You can purchase 1 products at a discounted price up to 15% discount.