for Loop
A control structure in shell scripting that allows you to iterate over lists, ranges, and command outputs for automation and repetitive tasks.
Syntax
for variable in list; do
commands
done
for ((initialization; condition; increment)); do
commands
done
for variable in {start..end..step}; do
commands
done
The for loop provides multiple ways to iterate over data in shell scripts, from simple list iteration to C-style loops and brace expansion.
Basic Usage
Iterate over a list
# Simple list iteration
for item in apple banana cherry; do
echo "Processing: $item"
done
# With variable assignment
fruits="apple banana cherry"
for fruit in $fruits; do
echo "Fruit: $fruit"
done
Basic iteration over a predefined list of items
Iterate over a range
# Numeric range
for i in {1..5}; do
echo "Number: $i"
done
# Range with step
for i in {0..10..2}; do
echo "Even number: $i"
done
# Reverse range
for i in {5..1}; do
echo "Countdown: $i"
done
Use brace expansion to iterate over numeric ranges
C-style for loop
# Traditional C-style loop
for ((i=0; i<5; i++)); do
echo "Index: $i"
done
# With different increment
for ((i=10; i>0; i-=2)); do
echo "Decrement: $i"
done
C-style syntax for more complex loop control
Advanced Usage
Iterate over command output
# Iterate over files in directory
for file in $(ls *.txt); do
echo "Processing file: $file"
done
# Iterate over process IDs
for pid in $(pgrep bash); do
echo "Bash process: $pid"
done
# Iterate over command arguments
for arg in "$@"; do
echo "Argument: $arg"
done
Use command substitution to iterate over dynamic content
Nested loops
# Nested for loops
for i in {1..3}; do
for j in {a..c}; do
echo "Position: $i$j"
done
done
# Matrix-like iteration
for row in {1..3}; do
for col in {1..3}; do
echo -n "[$row,$col] "
done
echo
done
Combine multiple loops for complex iteration patterns
Conditional iteration
# Break out of loop
for i in {1..10}; do
if [ $i -eq 5 ]; then
break
fi
echo "Number: $i"
done
# Continue to next iteration
for i in {1..10}; do
if [ $((i % 2)) -eq 0 ]; then
continue
fi
echo "Odd number: $i"
done
Control loop execution with break and continue statements
Practical Examples
File operations
# Process all text files
for file in *.txt; do
if [ -f "$file" ]; then
echo "Processing: $file"
# Add your processing logic here
fi
done
# Backup multiple files
for file in important1.txt important2.txt important3.txt; do
if [ -f "$file" ]; then
cp "$file" "${file}.backup"
echo "Backed up: $file"
fi
done
Common file processing tasks using for loops
System administration
# Check multiple services
for service in ssh apache2 mysql nginx; do
if systemctl is-active --quiet $service; then
echo "$service is running"
else
echo "$service is not running"
fi
done
# Monitor multiple servers
for server in server1 server2 server3; do
if ping -c 1 $server >/dev/null 2>&1; then
echo "$server is reachable"
else
echo "$server is unreachable"
fi
done
Administrative tasks that benefit from iteration
Data processing
# Process CSV data
IFS=',' read -ra fields <<< "name,age,city"
for field in "${fields[@]}"; do
echo "Field: $field"
done
# Generate sequence
for i in {1..100}; do
if [ $((i % 3)) -eq 0 ] && [ $((i % 5)) -eq 0 ]; then
echo "FizzBuzz: $i"
elif [ $((i % 3)) -eq 0 ]; then
echo "Fizz: $i"
elif [ $((i % 5)) -eq 0 ]; then
echo "Buzz: $i"
fi
done
Data manipulation and algorithm examples
Best Practices
for Loop Best Practices
- Always quote variables to handle spaces and special characters
- Use meaningful variable names for clarity
- Check if files exist before processing them
- Use break and continue for better control flow
- Consider performance for large iterations
- Use arrays for complex data structures
Common Pitfalls
- Word splitting - Variables with spaces can cause unexpected behavior
- Glob expansion - No matching files can cause errors
- Infinite loops - Ensure loop conditions will eventually be false
- Variable scope - Variables modified in loops persist after the loop
- Performance - Large iterations can be slow, consider alternatives