Chapter 5: Loops in Bash
Learn about loops in Bash, including for
, while
, and until
loops, to automate repetitive tasks and iterate over data effectively.
In this chapter, we’ll explore the different types of loops available in Bash scripting, allowing you to automate tasks that require repetitive actions or processing data in a structured way.
The for
Loop
The for
loop is used to iterate over a list of items, executing the same code block for each item. This loop is ideal for tasks where the number of iterations is known beforehand.
# Example: Basic for loop
for i in {1..5}; do
echo "Iteration $i"
done
This example prints "Iteration 1" through "Iteration 5" by iterating over the sequence from 1 to 5.
Iterating Over Arrays with for
You can also use the for
loop to iterate over arrays, making it useful for handling lists of items in Bash:
# Example: for loop with an array
fruits=("apple" "banana" "cherry")
for fruit in "${fruits[@]}"; do
echo "Fruit: $fruit"
done
In this example, the loop iterates over each element in the fruits
array and prints it.
The while
Loop
The while
loop executes as long as a specified condition is true. This loop is useful when you don’t know the exact number of iterations ahead of time.
# Example: Basic while loop
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
Here, the loop continues to execute as long as count
is less than or equal to 5, incrementing count
with each iteration.
Infinite Loops with while
A while
loop can create an infinite loop if the condition never becomes false. Use the break
statement to exit the loop when needed:
# Example: Infinite loop with break
while true; do
echo "Press CTRL+C to stop"
sleep 1
done
The until
Loop
The until
loop is similar to the while
loop, but it executes until a specified condition becomes true. This loop is helpful when you want the loop to continue until a certain condition is met.
# Example: Basic until loop
count=1
until [ $count -gt 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
This example continues looping until count
is greater than 5, incrementing count
with each iteration.
Controlling Loop Execution
Bash provides several commands to control loop behavior:
break
: Exits the loop immediately, skipping any remaining iterations.continue
: Skips the current iteration and moves to the next one.
# Example: Using break and continue
for i in {1..5}; do
if [ $i -eq 3 ]; then
echo "Skipping 3"
continue
fi
if [ $i -eq 5 ]; then
echo "Stopping at 5"
break
fi
echo "Number: $i"
done
In this example, the loop skips printing "3" and stops altogether when it reaches "5" due to the continue
and break
statements.
Summary and Next Steps
In this chapter, you learned how to use for
, while
, and until
loops to control repetitive tasks in Bash. In the next chapter, we’ll look at functions in Bash scripting, which allow you to create reusable code blocks for better script organization and efficiency.