For Loop
The for
loop is used to iterate over a list of items. It is particularly useful when you know the number of iterations in advance. Here’s the basic syntax:
Basic syntax
for item in list
do
# Commands to execute
done
Example
for i in {1..5}
do
echo "Iteration $i"
done
Output
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
While Loop
The while
loop continues to execute as long as a specified condition is true. It is useful when the number of iterations is not known beforehand.
Basic syntax
while [ condition ]
do
# Commands to execute
done
Example
count=1
while [ $count -le 5 ]
do
echo "Count is $count"
((count++))
done
This loop will print the count from 1 to 5.
Until Loop
The until
loop is similar to the while
loop, but it continues to execute as long as the specified condition is false.
Basic syntax
until [ condition ]
do
# Commands to execute
done
Example
count=1
until [ $count -gt 5 ]
do
echo "Count is $count"
((count++))
done
This loop will also print the count from 1 to 5.