How to Use the seq Command to Generate Number Sequences in Linux

When you are writing bash scripts in Linux, you often need to generate a list of numbers. Perhaps you need to create 100 uniquely numbered files (file1.txt, file2.txt, etc.), or you need to loop through a specific range of server IP addresses.

Rather than typing out long arrays manually, you can use the seq (sequence) command to instantly print a list of numbers directly to your terminal.

The Basic Syntax

The simplest way to use seq is to provide a single number. This tells the command to start at 1 and count up to your target number.

seq 5

Output:

1
2
3
4
5

Setting a Start and End Range

If you don’t want to start at number 1, you can provide two arguments: the starting number and the ending number.

seq 10 15

Output:

10
11
12
13
14
15

Adding an Increment (Step)

What if you only want to print even numbers, or count by fives? The seq command accepts three arguments: Start, Increment, and End.

To count from 0 to 20, jumping by 5 each time, you would type:

seq 0 5 20

Output:

0
5
10
15
20

You can also use negative increments to count backward! For example, seq 5 -1 1 will print 5, 4, 3, 2, 1.

Using seq in Bash Loops

While printing numbers to the screen is neat, seq is most powerful when combined with a for loop in a bash script to automate repetitive tasks.

For example, if you wanted to quickly create 10 empty files named document_1.txt through document_10.txt, you could run this one-liner in your terminal:

for i in $(seq 1 10); do touch document_$i.txt; done

The shell executes the seq 1 10 command first, generating the numbers. The for loop then takes each number, assigns it to the variable $i, and runs the touch command to create the file.

Formatting the Output with Leading Zeros

If you are generating files (like file_1.txt to file_10.txt), standard alphabetical sorting can cause issues (file 10 will often be sorted immediately after file 1, before file 2). To fix this, you should use leading zeros.

You can tell seq to automatically pad the numbers with zeros using the -w (width) flag.

seq -w 8 12

Output:

08
09
10
11
12

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.

Receive our best articles and tips delivered straight to your inbox.