Shell for loop: generate a sequence of numbers in Shell
For loop is one of the most frequently used command in shell. In this post, we show how to generate a sequence of numbers in shell, and use for loop to print out the numbers.
How to generate a range of number in Shell or Bash.
The answer is using the
seq command, here is the
seq command syntax:
seq FIRST LAST
seq FIRST INCREMENT LAST
Generate a sequence from 1 to 10
To generate a sequence of numbers from 1 to 10, we can use both
seq 10 or
seq 1 10.
Generate a sequence of numbers from 5 to 10
To generate a sequence of numbers from 5 to 10, we can use
seq 5 10 command.
Generate a sequence of even numbers from 4 to 16
We can use the following command to generate a sequence of even numbers from 4 to 16.
seq 4 2 16
4 is the start number,
16 is the end number, and
2 is the step
Generate a sequence of even numbers from 20 to 12
The following command can be used to generate a sequence of even number from 20 to 12:
seq 20 -2 12
Use seq command in shell for loop
We can use seq command in shell or bash for loop. See the following example:
for i in $(seq 2 2 10) ;
echo "number = $i"
Here is the output:
number = 2
number = 4
number = 6
number = 8
number = 10