In BASIC you have
FOR n = 1 TO 10
NEXT
In PHP you have
for ($n = 1; $n <= 10; $++) {
}
And finally, in bash shell scripting you have
for n in `seq 10`
do
done
Meet seq. It's one of those delightful little shell utilities, and it does one thing only and does it well. You give it a number and it will output a list of those number starting from 1. Observe:
[drt@localhost drt]$ seq 10
1
2
3
4
5
6
7
8
9
10
Hence the name 'seq' - it prints out a sequence of numbers. However, it can take up to three numbers as an argument, and this allows it to make any sequence of numbers in arithmetical progression. I'll tell you how to do that a bit later.
If given only one integer argument, seq will simply spit out a list of numbers from 1 to that integer. If given two arguments, seq will print out a list of numbers between the first argument and the second. Observe:
[drt@localhost drt]$ seq 4 8
4
5
6
7
8
Cool, non? But it gets better. If you give three, count 'em, three integer arguments to seq, then it will output a list of numbers, starting at the first argument, and going up to the third argument. But it will use the second argument as an increment instead of 1. It's kind of hard to explain, so I think some examples will best demonstrate this:
[drt@localhost drt]$ seq 65 32 399
65
97
129
225
257
289
321
353
385
[drt@localhost drt]$ seq 2 4 23
2
6
10
14
18
22
Seq also has some neat options which can make life a lot easier. Three of them, to be exact. These are -f, -s and -w. -f can be used to specify the format of seq's output. It uses a printf style format string, and by default is "%g". -s lets you set what seq uses to separate each of the numbers in its output (by default it's \n, but it may be useful to set it to something like a space. Finally, there's -w which, if used, will make all of the numbers equal length by padding them with zero. If you're outputting from 1 to 999 and use the -w switch then you'll get numbers like 004, 012 and 068 instead of just 4, 12 and 68.
And no overview of this would be complete without examples.
Getting a list of ten pseudorandom numbers
$ for n in `seq 10`; do echo $RANDOM; done
Outputting every second user in /etc/passwd
$ x=`wc /etc/passwd | awk '{print $1}'`; for n in `seq 2 2 $x`; do awk "NR==$n" /etc/passwd; done
Annoying everyone else with mesg permissions turned on
$ for n in `seq 10000`; do wall "test"; done
Finding prime factors of a series of numbers
$ for n in `seq 10000`; do factor $n; done
The contents of this writeup are in the public domain.