The for
loop in Bash is used to iterate over a sequence of values. It has the following syntax:
for variable in sequence
do
# Commands to be executed for each iteration
done
variable
: Represents the loop variable that takes each value in the specified sequence.sequence
: Can be a range of numbers, a list of items, or the output of a command.
Example:
for i in {1..5}
do
echo "Iteration $i"
done
This will print:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
The while
loop in Bash continues to execute a block of commands as long as a specified condition is true. Here is the basic syntax:
while [ condition ]
do
# Commands to be executed as long as the condition is true
done
condition
: Represents the test that determines whether the loop continues or terminates.
Example:
counter=1
while [ $counter -le 5 ]
do
echo "Iteration $counter"
((counter++))
done
This will print the same output as the previous for
loop example.
The until
loop is similar to the while
loop, but it continues to execute a block of commands as long as a specified condition is false. The syntax is as follows:
until [ condition ]
do
# Commands to be executed as long as the condition is false
done
Example:
counter=1
until [ $counter -gt 5 ]
do
echo "Iteration $counter"
((counter++))
done
This will also produce the same output as the previous examples.
Understanding the for
, while
, and until
loops in Bash is crucial for efficient scripting in Linux. These constructs provide flexibility in handling repetitive tasks and iterating over data, making them fundamental elements in shell scripting/Linux.