This tutorial is about multiple ways to iterate the range of numbers stored in variables and print them to the console.

In this example, Generate a sequence of a range of numbers and store it in a variable.

Sometimes, We want to generate file names with names containing numbers generated from a sequence or range of numbers.

Generate a range of numbers in the bash script

  • using seq seq tool generates a sequence of numbers.
number=4
for k in $(seq 1 $number); do echo $k; done

Output:

1
2
3
4
  • using for loop
number=5
for ((k=1;k<=number;k++)); do
    echo $k
done

Output:

1
2
3
4
5
  • while loop

number=5
k=1 ;
while [[ $k -le $number ]] ; do
    echo $k
    ((k = k + 1))
done

Conclusion

seq is better compared with for and while loop