Bash For Loops - Iterating Over Lists, Ranges, and Files
Complete guide to bash for loops including list iteration, C-style loops, range expressions, file globbing, and command output iteration with practical examples.
Detailed Explanation
For Loops in Bash
For loops are one of the most versatile control flow constructs in bash. They allow you to iterate over lists, ranges, file patterns, and command output.
Basic List Iteration
The simplest form iterates over a space-separated list:
for fruit in apple banana cherry; do
echo "I like $fruit"
done
Range Expressions
Bash supports brace expansion for numeric ranges:
# Simple range
for i in {1..10}; do
echo "Number: $i"
done
# Range with step
for i in {0..100..5}; do
echo "Value: $i"
done
C-Style For Loop
For more control over iteration, use C-style syntax:
for ((i=0; i<10; i++)); do
echo "Iteration $i"
done
# Nested loops
for ((i=1; i<=3; i++)); do
for ((j=1; j<=3; j++)); do
echo "($i, $j)"
done
done
Iterating Over Files
File globbing lets you process matching files:
# Process all log files
for file in *.log; do
echo "Compressing $file"
gzip "$file"
done
# Process files in subdirectories
for file in src/**/*.ts; do
echo "Checking $file"
done
Command Output Iteration
Iterate over the output of a command:
# Process each line of a command's output
for user in $(cut -d: -f1 /etc/passwd); do
echo "User: $user"
done
# Process files found by find
for file in $(find . -name "*.tmp" -type f); do
rm "$file"
done
Practical Examples
# Batch rename files
for file in *.jpeg; do
mv "$file" "${file%.jpeg}.jpg"
done
# Check multiple servers
for server in web{1..5}.example.com; do
ping -c 1 -W 2 "$server" > /dev/null 2>&1 \
&& echo "$server: UP" \
|| echo "$server: DOWN"
done
# Process CSV rows
while IFS=',' read -r name email role; do
echo "Creating account for $name ($email) as $role"
done < users.csv
Note: When iterating over filenames that may contain spaces, always quote the variable: "$file" instead of $file.
Use Case
For loops are used in virtually every bash script. Common use cases include batch file processing (renaming, converting, compressing), server health checks across multiple hosts, automated deployments to multiple environments, log rotation scripts, and data processing pipelines. They are essential for any task that requires repetitive operations.
Try It — Bash Cheat Sheet
Related Topics
Bash If/Else Conditions - Tests, Comparisons, and File Checks
Control Flow
Bash While and Until Loops - File Reading, Polling, Counters
Control Flow
Bash Functions - Definition, Arguments, Return Values, Scope
Control Flow
Bash Text Processing - grep, sed, awk, sort, cut
Text Processing
Bash File Operations - ls, cp, mv, rm, find, chmod
File Operations