Loops solve one of programming's most common challenges: performing repetitive tasks efficiently. Instead of copying and pasting the same commands dozens or hundreds of times, you can wrap those commands in a loop and let the computer handle the repetition for you. This not only makes your scripts shorter and cleaner but also makes them easier to maintain and modify.
Whether you need to process a list of files, count from 1 to 100, or keep trying something until it succeeds, loops provide the perfect tool for the job. Let's explore how these digital repeat buttons can transform your scripting from tedious to powerful!
The For Loop
When to Use For Loops
- When you have a list of items to process (files, directories, strings, etc.)
- When you need to repeat an action a specific number of times
- When processing array elements or command output
- When you know exactly how many iterations you need
- When iterating over a sequence of numbers
Common For Loop Options
Syntax |
What It Does |
When to Use It |
for var in item1 item2 ... |
Loops through a list of specified items |
When you have a predefined list |
for var in $(command) |
Loops through command output |
When processing the result of a command |
for var in {1..10} |
Loops through a range of numbers |
When iterating a specific number of times |
for var in *.txt |
Loops through files matching a pattern |
When processing files of a specific type |
for ((i=0; i<5; i++)) |
C-style for loop with initialization, condition, and increment |
When you need more control over the loop counter |
Practical Examples
# Basic for loop with list
for name in Alice Bob Charlie Dave; do
echo "Hello, $name!"
done
# Loop through a range of numbers
for num in {1..5}; do
echo "Number: $num"
done
# Process all text files in current directory
for file in *.txt; do
echo "Processing $file..."
wc -l "$file" # Count lines in each file
done
# Use command output in a loop
for user in $(cat users.txt); do
echo "Creating home directory for $user"
# mkdir /home/$user # Commented out for safety
done
# C-style for loop
for ((i=0; i<5; i++)); do
echo "Iteration $i"
done
The While Loop
When to Use While Loops
- When you need to repeat until a condition changes
- When processing input line by line
- When you need to wait for something to happen
- When the number of iterations isn't known in advance
- When implementing counters or timers
Common While Loop Options
Syntax |
What It Does |
When to Use It |
while [[ condition ]] |
Repeats while condition is true |
When looping based on a Boolean condition |
while read line |
Processes input line by line |
When processing file contents or command output |
while : # (colon is always true) |
Creates an infinite loop |
When implementing services or monitors that run until manually stopped |
Practical Examples
# Basic while loop with counter
count=1
while [[ $count -le 5 ]]; do
echo "Count: $count"
count=$((count + 1))
done
# Read file line by line
while read line; do
echo "Line: $line"
done < input.txt
# Wait for a file to exist
while [[ ! -f /tmp/signal_file ]]; do
echo "Waiting for signal file..."
sleep 5
done
echo "Signal file detected!"
# Menu system with while loop
choice=""
while [[ "$choice" != "q" ]]; do
echo "Menu:"
echo "1. Show date"
echo "2. List files"
echo "q. Quit"
read -p "Enter choice: " choice
case $choice in
1) date ;;
2) ls -la ;;
q) echo "Exiting..." ;;
*) echo "Invalid choice" ;;
esac
done
The Until Loop
When to Use Until Loops
- When you want to repeat until a condition becomes true
- When waiting for something to become available
- When the exit condition is more naturally expressed than the continuation condition
- When implementing retries until success
- When a process needs to run until completion
Common Until Loop Options
Syntax |
What It Does |
When to Use It |
until [[ condition ]] |
Repeats until condition becomes true |
When the exit condition is clearer than the continuation condition |
Practical Examples
# Basic until loop with counter
count=1
until [[ $count -gt 5 ]]; do
echo "Count: $count"
count=$((count + 1))
done
# Retry a command until it succeeds
until ping -c 1 example.com &> /dev/null; do
echo "Waiting for network connection..."
sleep 5
done
echo "Network is up!"
# Wait until a specific time
current_time=$(date +%H%M)
until [[ $current_time -ge 0900 ]]; do
echo "Waiting for 9:00 AM. Current time: $current_time"
sleep 60
current_time=$(date +%H%M)
done
echo "It's 9:00 AM or later, starting process..."
Advanced Loop Techniques
When to Use Advanced Techniques
- When you need to exit loops early
- When you want to skip certain iterations
- When implementing complex nested loops
- When combining loops with decision making
- When processing complex data structures
Advanced Loop Techniques
Technique |
What It Does |
When to Use It |
Nested loops |
Puts one loop inside another |
When processing multi-dimensional data or combinations |
break |
Exits the current loop |
When a termination condition is met mid-loop |
continue |
Skips to the next iteration |
When certain items should be skipped |
Loop with if/else |
Adds conditional logic inside loops |
When different actions are needed for different items |
Practical Examples
# Nested loops
for i in {1..3}; do
for j in {a..c}; do
echo "Combination: $i$j"
done
done
# Using break to exit a loop early
for num in {1..10}; do
if [[ $num -eq 5 ]]; then
echo "Reached 5, stopping loop"
break
fi
echo "Number: $num"
done
# Using continue to skip iterations
for num in {1..5}; do
if [[ $num -eq 3 ]]; then
echo "Skipping 3"
continue
fi
echo "Processing: $num"
done
# Loop with if/else logic
for file in *.txt; do
if [[ -s "$file" ]]; then
echo "$file has content, processing..."
else
echo "$file is empty, skipping"
fi
done
# Processing user input in a loop with exit condition
while true; do
read -p "Enter a command (or 'quit' to exit): " cmd
if [[ "$cmd" == "quit" ]]; then
echo "Exiting..."
break
fi
# Process the command
echo "Executing: $cmd"
eval "$cmd"
done
Summary
Loops are fundamental building blocks in Bash scripting that allow you to automate repetitive tasks efficiently. Whether you're using a for loop to process items in a list, a while loop to repeat until a condition changes, or an until loop to wait for something to happen, mastering loops will dramatically increase your scripting capabilities.
By combining loops with other scripting elements like conditional statements, variables, and functions, you can create powerful scripts that process data, automate tasks, and solve complex problems. The time you invest in understanding loops will pay dividends in the efficiency and capability of your Bash scripts.