How do I write a 'for' loop in Bash?
Categories:
Mastering 'for' Loops in Bash: A Comprehensive Guide

Learn the various syntaxes and practical applications of 'for' loops in Bash scripting to automate repetitive tasks and process data efficiently.
The for
loop is a fundamental construct in Bash scripting, allowing you to iterate over a list of items, a range of numbers, or the output of a command. Understanding its different forms is crucial for writing effective and efficient shell scripts. This article will guide you through the various ways to write for
loops in Bash, complete with examples and best practices.
Basic 'for' Loop: Iterating Over a List
The most common form of the for
loop in Bash iterates over a space-separated list of words. This list can be explicitly defined, come from a variable, or be the result of command substitution. Each item in the list is assigned to the loop variable in sequence, and the commands within the loop body are executed for each item.
for item in item1 item2 item3;
do
echo "Processing: $item"
done
Basic 'for' loop iterating over an explicit list of strings.
FILES=$(ls *.txt)
for file in $FILES;
do
echo "Found text file: $file"
done
Iterating over the output of a command (e.g., ls
).
for file in *;
or find . -type f -print0 | xargs -0 -I {} ...
to handle filenames with spaces or special characters correctly. The example above is simplified for demonstration.C-Style 'for' Loop: Iterating with Numeric Ranges
Bash also supports a C-style for
loop syntax, which is ideal for iterating through numeric sequences. This syntax is familiar to programmers coming from languages like C, Java, or JavaScript, and it provides explicit control over the initialization, condition, and increment of the loop variable.
for (( i=1; i<=5; i++ ));
do
echo "Count: $i"
done
C-style 'for' loop for numeric iteration from 1 to 5.
for (( j=10; j>=0; j-=2 ));
do
echo "Countdown by 2: $j"
done
C-style 'for' loop demonstrating a decrementing step.
flowchart TD A[Start Loop] --> B{"Initialize i=1"} B --> C{"Is i <= 5?"} C -- Yes --> D[Execute Loop Body] D --> E["Increment i (i++)"] E --> C C -- No --> F[End Loop]
Flowchart illustrating the logic of a C-style 'for' loop.
Sequence Expression 'for' Loop: Simple Numeric Ranges
For simple numeric ranges, Bash offers a more concise syntax using brace expansion {start..end}
or {start..end..step}
. This is often preferred for its readability when dealing with straightforward integer sequences.
for num in {1..5};
do
echo "Number: $num"
done
Iterating through a simple numeric range from 1 to 5.
for char in {a..e};
do
echo "Character: $char"
done
Iterating through a range of characters.
for i in {0..10..2};
do
echo "Even number: $i"
done
Iterating with a step value (e.g., even numbers).
{start..end}
generates the entire sequence before the loop starts. For very large ranges, this can consume significant memory. In such cases, the C-style for ((...))
loop is generally more memory-efficient as it generates numbers on the fly.Looping Through Array Elements
Bash arrays are powerful for storing collections of items. You can easily iterate through all elements of an array using the @
or *
special parameters within the array expansion.
declare -a FRUITS=("Apple" "Banana" "Cherry" "Date")
for fruit in "${FRUITS[@]}";
do
echo "I like $fruit."
done
Iterating through all elements of a Bash array.
"${ARRAY[@]}"
when iterating through array elements to ensure that items containing spaces are treated as single elements, preventing word splitting issues.