seq - Linux


Overview

The seq command in Linux generates a sequence of numbers, which can be customized with starting and increment values. The primary purpose of seq is to create numeric sequences, commonly used in scripting and loop control in shell scripts.

Syntax

The basic syntax of the seq command is:

seq [OPTION]... LAST
seq [OPTION]... FIRST LAST
seq [OPTION]... FIRST INCREMENT LAST

Here, FIRST, INCREMENT, and LAST are numeric values. FIRST and INCREMENT are optional; if omitted, FIRST defaults to 1 and INCREMENT defaults to 1.

Options/Flags

  • -f, --format=FORMAT: Specify a printf-style format for the numbers. The default is %.f.
  • -s, --separator=STRING: Use STRING to separate numbers. The default is \n.
  • -w, --equal-width: Equalize width by padding with leading zeroes.
  • --help: Display a help message and exit.
  • --version: Output version information and exit.

Examples

  1. Simple Sequence: Generate numbers from 1 to 5.

    seq 5
    
  2. Specify Range: Create a sequence from 2 to 10.

    seq 2 10
    
  3. Custom Increment: Generate numbers from 0 to 10 in increments of 2.

    seq 0 2 10
    
  4. Formatted Output: Format the output to have two digits.

    seq -f "%02g" 5
    
  5. Alternate Separator: Print numbers from 1 to 5, separated by commas.

    seq -s "," 5
    

Common Issues

  • Formatting Issues: Users often forget that default output ends in newline characters. For comma separation, using -s "," will not append a comma to the last number.
  • Using Non-Numeric Arguments: seq expects numeric arguments for FIRST, INCREMENT, and LAST. Providing non-numeric arguments will result in an error. Ensure all inputs are numeric.

Integration

seq is often used in shell scripts to control loop executions. For example, in a bash for-loop to run a command 5 times:

for i in $(seq 5);
do
   echo "Iteration $i"
done

Combine seq with awk for advanced numeric processing:

seq 10 10 50 | awk '{print $1, $1*$1}'

This generates numbers from 10 to 50 in steps of 10 and also prints their squares.

  • echo: Often used with seq for generating formatted output.
  • for: Utilizes output from seq in shell loops.
  • awk: Can process seq output for complex number manipulation.

Further reading and more detailed information about the seq command can be explored in the GNU coreutils online pages, available here.