Skip to content
Linux Basics: Generate Controlled Numeric Sequences with GNU seq

Linux Basics: Generate Controlled Numeric Sequences with GNU seq

October 27, 2026

A shell loop or small fixture may need a predictable sequence of numbers. GNU seq handles explicit start, step, and end values and can format each number. Keep the sequence small and choose numeric rules deliberately.

Prepare a scratch directory

Tested on Linux with GNU coreutils 9.7 and GNU Bash 5.2.37. You need the named runtime, Bash, a text editor, and the standard mktemp, rm, and rmdir utilities. The script creates a separate temporary fixture directory and removes only that directory on exit. It does not operate on your existing files.

Keep using the same terminal. Stop if setup fails, before saving the source:

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Run the example

Save this as demonstrate-gnu-seq.sh:

#!/usr/bin/env bash
set -euo pipefail
export LC_ALL=C
fixture_dir="$(mktemp -d)"
trap 'rm -rf -- "$fixture_dir"' EXIT
cd -- "$fixture_dir"
printf 'Ascending by two:\n'
seq 2 2 8 > values.txt
cat values.txt
test "$(wc -l < values.txt)" -eq 4
printf 'Descending:\n'
seq -s ',' 3 -1 1
printf 'Padded labels:\n'
seq -f 'item-%03g' 1 3
printf 'A range with no values:\n'
seq 3 1 1 > empty.txt
test ! -s empty.txt
printf 'Empty output verified\n'

Run it:

bash demonstrate-gnu-seq.sh

Observed output:

Ascending by two:
2
4
6
8
Descending:
3,2,1
Padded labels:
item-001
item-002
item-003
A range with no values:
Empty output verified

Read the result

The first range includes its reachable endpoint. A negative increment walks downward; -s selects the separator between values. -f controls the output format and must contain a supported floating-point conversion, so %03g is used for these small integer labels. A positive step cannot reach a smaller final value, yielding empty output rather than an error.

Apply it carefully

seq accepts floating-point values, so do not rely on it for exact decimal arithmetic or arbitrarily large integer identifiers. Rounding can affect a range near its endpoint. Use a locale such as C when numeric separators must be stable. Avoid expanding enormous output through command substitution; feed bounded values through a pipeline or a read loop when practical.

The official reference describes the API and its options. The checks above cover the specific fixture, not every possible input or environment.

Clean up

Remove the source and then the empty practice directory:

rm -- demonstrate-gnu-seq.sh
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

If the directory is not empty, inspect the remaining files rather than deleting unknown contents.

Acknowledgements

This post was created with assistance from AI.

Last updated on