To iterate over a range of numbers defined by variables in Bash, use one of the following methods:
1. C-style for
Loop (Recommended)
The most efficient and modern approach, supported in Bash 3.0+.
Syntax:
start=3
end=7
for ((i = start; i <= end; i++)); do
echo "$i"
done
Output:
3
4
5
6
7
With a Step Value:
step=2
for ((i = start; i <= end; i += step)); do
echo "$i"
done
Output:
3
5
7
2. Using seq
(Portable)
Works on most systems but relies on the external seq
command.
Basic Usage:
for i in $(seq "$start" "$end"); do
echo "$i"
done
With a Step Value:
step=2
for i in $(seq "$start" "$step" "$end"); do
echo "$i"
done
3. Brace Expansion with eval
(Caution)
Use eval
to expand variables in brace syntax. Only use this if you control the input.
Syntax:
for i in $(eval echo "{$start..$end}"); do
echo "$i"
done
Key Notes
- C-style Loop: Best for modern scripts (no external dependencies).
seq
: Useful for stepping or backward ranges (e.g.,seq 10 -2 3
).- Error Handling: Ensure
start
andend
are integers. - Reverse Ranges: Use
for ((i = start; i >= end; i--))
.
Examples
Backward Iteration
start=5
end=1
for ((i = start; i >= end; i--)); do
echo "$i"
done
Output:
5
4
3
2
1
Negative Numbers
start=-2
end=2
for ((i = start; i <= end; i++)); do
echo "$i"
done
Output:
-2
-1
0
1
2
Common Pitfalls
- Variables Not Integers: Validate input (e.g.,
[[ $start =~ ^-?[0-9]+$ ]]
). - Start > End: Handle reverse ranges explicitly (use
i--
instead ofi++
).
Choose the method that best fits your script’s requirements!