OS X: Double-click Shell Scripts

Normally, shell scripts can only be executed from the command line. For convenience, especially for users who don’t use Terminal, shell scripts can be made double-clickable in the Finder: simply have the suffix be “.command”, and change the permissions to read/execute.

By default, such scripts execute within the user’s home directory. In some cases, you might want the script to run in its own directory, or some arbitrary directory (such as, say, /tmp). Such a path might contain shell-hostile things like spaces, special characters, etc., and  so this common shell technique will not work:

cd `dirname $0`

The trick is to do this:

cd "$(dirname "$0")"