Shaun ONeil

Counting to ten

A recent query on how to do:

for i in `seq 1 10`
do
    echo $i
done

under OSX, as it doesn't have the 'seq' command. Easy answer. Don't!

In bash 3, you can do this built-in with:

for i in {1..10}
do
    echo $i
done

Stepping is a bit more awkward. For every second step, Bash 4 allows us:

for i in {1..10..2}
do
    echo $i
done

but OSX doesn't have bash4 because GPLv3 is evil. So roll up your sleeves and loop like a grown-up.

for ((i=1;i<=10;i=i+2))
do
    echo $i
done

For some bonus points .. one thing I always liked 'seq' for, was being able to add leading zeroes.

for i in `seq -w 1 10`
do
    echo $i
done

gives us 01, 02, 03, 04, 05, 06, 07, 08, 09, 10. Handy.

Bash can do that too :)

for i in {1..10}
do
    printf "%02d\n" $i
done

Starting to look familiar?

The trick here, is that if you start leaning on stuff like seq from GNU coreutils, or jot on BSD & OSX, your scripts start randomly exploding when you move between platforms. If you just write bash scripts using, well, bash, you run wherever bash does.

This message brought to you by 2004.