seq shell command replacement for Mac OS X

There are several ways to write shell script for loops, but I have found their compatibility doesn’t depend only on the shell you are using, but the operating system as well.

I personally like using the /usr/bin/seq command with a syntax like this:

for i in seq ${1} ${2}

where $1 and $2 are my command-line arguments specifying the integer start and stop of my loop. However, Mac OS X does not ship with the seq command. Here is a shell script you can place in the /usr/bin/ directory. It will then be on your path for use in any scripts you write. I use “echo -n” instead of printf so that it will properly handle negative numbers, though the -n option may not be available with your distribution.

#!/bin/bash

if [ $# -eq 2 ] then let from=”$1”; let to=”$2”; elif [ $# -eq 1 ] then let from=”0”; let to=”$1”; else echo “Usage: seq [from] [to]” exit 1; fi

while [ $from -lt $to ] do echo -n “$from “; from=$[$from+1] done echo -n “$from “; {% endhighlight %}