Note also that there's a more feature complete version that accomplishes the same tasks in the contrib directory of git (http://git.kernel.org/?p=git/git.git;a=blob;f=contrib/comple...).
It's implemented in bash but I use it with almost no modification with the Korn shell.