Bash: How to Generate a Sequence of Numbers


Often you may want to use Bash to generate a sequence of numbers.

The easiest way to do so is by using the sequence expression, which uses the following syntax:

{start..end..increment}

where:

  • start: The starting value
  • end: The ending value
  • step: Number to increment by (if not specified, then default is 1)

There are three common ways to use this syntax in practice:

Method 1: Generate Sequence of Numbers in Ascending Order

echo {0..10}

This particular example will return the numbers 1 through 10 in ascending order.

Method 2: Generate Sequence of Numbers in Descending Order

echo {10..0}

This particular example will return the numbers 10 through 1 in descending order.

Method 3: Generate Sequence of Numbers with Specific Step

echo {0..10..2}

This particular example will return the numbers 1 through 10, using a step value of 2.

The following examples show how to use each of these methods in practice.

Example 1: Generate Sequence of Numbers in Ascending Order Using Bash

We can use the following syntax in Bash to generate a sequence of numbers ranging from 0 to 10 in ascending order:

echo {0..10}

The following screenshot shows how to use this syntax in practice:

Bash generate sequence of numbers

Notice that this produces a sequence of numbers ranging from 0 to 10.

Since we didn’t specify a value for the step argument, a default value of 1 was used.

Example 2: Generate Sequence of Numbers in Descending Order Using Bash

We can use the following syntax in Bash to generate a sequence of numbers ranging from 10 to 0 in descending order:

echo {10..0}

The following screenshot shows how to use this syntax in practice:

Bash sequence of numbers in descending order

Notice that this produces a sequence of numbers ranging from 10 to 0.

Since we didn’t specify a value for the step argument, a default value of 1 was used.

Example 3: Generate Sequence of Numbers with Specific Step Using Bash

We can use the following syntax in Bash to generate a sequence of numbers ranging from 0 to 10 using a step value of 2:

echo {0..10..2}

The following screenshot shows how to use this syntax in practice:

Bash sequence of numbers with specific step value

Notice that this produces a sequence of numbers ranging from 0 to 10 with a step value of 2.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Generate Random Number in Range
Bash: How to Extract First Number from a String
Bash: How to Count Number of Characters in String

Leave a Reply