BASH Programming

How to Use seq Command in Bash

In Bash, the ‘seq’ command is a tool that generates a sequence of numbers. It can be used to create lists, loops, and perform various other tasks that require a range of integers. In this article, we will cover what the ‘seq’ command is and how to use it with three different examples.

What is ‘seq’ Command in Bash

The ‘seq’ command generates a sequence of numbers, which can be used for various purposes. It takes two arguments: the starting point and the ending point. By default, it increments by one, but it can be modified to increment by any value. The syntax for the ‘seq’ command is as follows:

seq [OPTION]... LAST

seq [OPTION]... FIRST LAST

seq [OPTION]... FIRST INCREMENT LAST

Here, the first argument is the starting number of the sequence, the second argument is the ending number, and the third argument (if specified) is the increment value. Let’s take a look at some examples.

Example 1

To illustrate the use of ‘seq’ I have given a shell script that prints the sequence of numbers from 1 to 10:

#!/bin/bash

for i in $(seq 1 10); do

echo $i

done

Here, the ‘seq’ command generates a sequence of numbers from 1 to 10, which is then used by the ‘for’ loop to iterate over the numbers and print them one by one:

Example 2

Here is another example that demonstrates the use of the ‘seq’ command, which prints the sequence of numbers from 10 to 1 in reverse order:

#!/bin/bash

for i in $(seq 10 -1 1); do

echo $i

done

Here, the ‘seq’ command generates a sequence of numbers from 10 to 1, decrementing by 1 at each step. The ‘for’ loop then prints the numbers in reverse order:

Conclusion

The ‘seq’ command is a useful tool in Bash for generating sequences of numbers. It can be used in a variety of contexts, including loops, lists, and more. By understanding how to use the ‘seq’ command, you can create complex scripts and perform more advanced tasks in your Bash programming.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.