Bash: Loop through a range of values

Bash offers us multiple possibilities to loop through a range of values. The range borders can be defined statically or dynamically.

Example 1. Looping through a range from 5 to 10 using for loop:

r="5 6 7 8 9 10"
for i in ${r}; do echo ${i}; done
Output:
5
6
7
8
9
10

Example 2. Looping through a dynamically defined range from 5 to 10 using for loop:

s=5
e=10
for i in $( seq ${s} ${e} ); do echo ${i}; done
Output:
5
6
7
8
9
10

In the previous example, we had the increment equal to one. The example 3 below shows how to loop though a dynamically defined range from 5 to 10 with the increment equal to 2. As in the previous examples, the for loop is used:

s=5
e=10
for i in $( seq ${s} 2 ${e} ); do echo ${i}; done
Output:
5
7
9

The final example 4 shows how to loop through a dynamically defined range, with start and length specified:

s=5
l=5
for i in $( seq ${s} $((${s} + ${l})) ); do echo ${i}; done
Output:
5
6
7
8
9
10