Lesson 4: Bash Control Structures – loops (for, while, until)
Welcome to Lesson 4: Bash Control Structures – Loops (for, while, until). Loops are a powerful feature in Bash scripting that allow you to perform repetitive tasks efficiently. In this lesson, we’ll explore the three main types of loops: for
, while
, and until
. You’ll learn how to use these loops to iterate over lists, process files, and manage complex tasks with minimal code. By the end, you’ll understand how to apply loops to automate repetitive actions and make your scripts more efficient. Let’s get started with mastering loops in Bash!
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
item
: A placeholder that stores the current value from thelist
during each iteration.list
: A sequence of items to iterate over. It can be a static list, a range of numbers, or output from a command.- Commands: These are executed in each iteration of the loop.
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
condition
: A logical test that determines if the loop continues. The condition can be any command or expression that returns a status of0
(true).- Commands: The operations performed on each iteration while the condition remains true.
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
condition
: A logical test that determines if the loop should stop. The condition is evaluated at the beginning of each iteration.- Commands: The block of code that executes while the condition remains false.
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.
Lesson 4: Bash Control Structures – loops (for, while, until)