Repeating Actions with Loops
Loops let you execute a block of commands repeatedly. They're essential for automation โ processing lists of files, retrying operations, counting, and more.
The for Loop
The for loop iterates over a list of items.
# Loop over a list of words
for fruit in apple banana cherry; do
echo "I like $fruit"
done
# Loop over files
for file in *.txt; do
echo "Processing: $file"
done
# Loop over a range of numbers
for i in {1..5}; do
echo "Number: $i"
done
# Range with step
for i in {0..20..5}; do
echo "Count: $i" # 0, 5, 10, 15, 20
done
# C-style for loop
for ((i = 0; i < 5; i++)); do
echo "Index: $i"
done{1..100} is expanded before the loop runs, so it's fast. For very large ranges, consider a while loop with arithmetic instead.
The while Loop
The while loop runs as long as a condition is true.
# Count to 5
count=1
while [[ $count -le 5 ]]; do
echo "Count: $count"
((count++))
done
# Infinite loop (be careful!)
while true; do
echo "Press Ctrl+C to stop"
sleep 1
doneThe until Loop
until is the opposite of while โ it runs until the condition becomes true.
count=1
until [[ $count -gt 5 ]]; do
echo "Count: $count"
((count++))
donebreak & continue
break exits the loop entirely. continue skips the rest of the current iteration and moves to the next one.
# break โ stop at 3
for i in {1..10}; do
if [[ $i -eq 4 ]]; then
break
fi
echo "$i"
done
# Output: 1 2 3
# continue โ skip even numbers
for i in {1..6}; do
if (( i % 2 == 0 )); then
continue
fi
echo "$i"
done
# Output: 1 3 5Reading Files Line by Line
A common pattern is to read a file one line at a time using a while loop:
# Read a file line by line
while IFS= read -r line; do
echo "Line: $line"
done < myfile.txt
# Process CSV data
while IFS=, read -r name age city; do
echo "$name is $age years old and lives in $city"
done < people.csvIFS= read -r to preserve whitespace and backslashes. Without these, lines may be mangled.
Try It Yourself
Summary
You've mastered for loops (list, range, C-style), while and until loops, break and continue, and reading files line by line. Loops are the engine behind most automation scripts.