seq
The seq command in Unix-like operating systems generates sequences of numbers, either in increasing or decreasing order. It's useful in shell scripting for iterating over a range of numbers or generating lists.
Basic Syntax
seq [options] [start] [increment] endoptions: Optional flags that modify the behavior of the
seqcommand.start: The starting number of the sequence (default is 1).
increment: The increment between numbers (default is 1).
end: The ending number of the sequence.
Examples
Generating a Sequence of Numbers
# Generate numbers from 1 to 5
seq 1 5Output:
1
2
3
4
5Specifying Start and End
# Generate numbers from 5 to 10
seq 5 10Output:
5
6
7
8
9
10Generating Numbers with Increment
# Generate numbers from 1 to 10 with increment of 2
seq 1 2 10Output:
1
3
5
7
9Generating a Sequence in Reverse Order
# Generate numbers from 10 to 1
seq 10 -1 1Output:
10
9
8
7
6
5
4
3
2
1Practical Use Cases
Looping with for and seq
for and seq# Loop through numbers from 1 to 5
for i in $(seq 1 5)
do
echo "Number: $i"
doneCreating Directories
# Create directories dir1 to dir5
for i in $(seq 1 5)
do
mkdir "dir$i"
doneFile Operations
# Create empty files file1.txt to file10.txt
for i in $(seq 1 10)
do
touch "file$i.txt"
doneAdvanced Examples
Using seq in a for Loop
seq in a for Loop# Print squares of numbers from 1 to 5
for i in $(seq 1 5)
do
echo "Square of $i is $(($i * $i))"
doneGenerating a Fixed-Length Sequence
# Generate a sequence of 10 numbers starting from 100
seq 100 109Output:
100
101
102
103
104
105
106
107
108
109Conclusion
The seq command is a handy tool in shell scripting for generating sequences of numbers efficiently. It simplifies tasks such as looping through ranges of numbers, creating directories or files in batches, and performing mathematical operations in scripts. By leveraging seq, you can make your shell scripts more dynamic and versatile.
Last updated