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

When writing bash scripts for Linux system administration, you frequently need to execute a command a specific number of times. Instead of manually typing out a list of numbers or writing a complex while loop with an incrementing counter variable, Linux provides a dedicated, highly efficient tool for generating lists of numbers: the seq (sequence) command. It instantly prints a sequence of integers or decimals, one per line, making it the perfect companion for standard for loops.

Generating Basic Number Sequences

The simplest way to use seq is to provide it with a single number. The command will assume you want to start at 1 and count up to your provided number.

seq 5

This will immediately output the numbers 1, 2, 3, 4, and 5, each on a new line.

If you want to start at a number other than 1, you must provide two arguments: the start value and the end value.

seq 10 14

This will output 10, 11, 12, 13, and 14.

Changing the Increment Step

By default, seq counts by ones. However, you can insert a third argument into the middle of the command to specify a custom increment step. The syntax becomes: seq [start] [step] [end].

To count from 0 to 20 by fives:

seq 0 5 20

This will output 0, 5, 10, 15, and 20. You can even use negative numbers as the step value to count backward.

seq 10 -2 4

This outputs 10, 8, 6, and 4.

Formatting the Output with Padding

If you are using seq to generate numbered filenames (e.g., file_01.txt, file_02.txt), a major problem arises when you reach double digits, as the alphabetical sorting of the files will become disorganized. To fix this, you must pad the single digits with leading zeros. seq can do this automatically using the -w (equal width) flag.

seq -w 8 12

The output will be perfectly padded to match the width of the largest number: 08, 09, 10, 11, 12.

Using seq in a Bash For Loop

The true power of seq is unleashed when you embed it inside a loop using command substitution (wrapping the command in $( ) or backticks). This allows you to iterate over the generated numbers.

for i in $(seq -w 1 5); do
  touch "backup_server_$i.log"
done

This simple script instantly creates five empty log files named backup_server_01.log through backup_server_05.log.

Get the best tech tips delivered straight to your inbox.

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