Allow .command files to determine working directory

Dec 20, '04 09:04:00AM

Contributed by: davemak

An earlier hint describes how you can use the .command filename suffix on a shell script to make it double-clickable in the Finder. This is very handy, but it turns out that such scripts start up with their current working directory set to the home directory of the current user. This makes it inconvenient to distribute .command files that come with additional resources that they expect to find via paths relative to the directory in which the .command file is located.

In order to set the current working directory of the running script to the folder in which the .command file is located, simply add this line at the top of the shell script:

cd `dirname $0`
Here's how this works: $0 is the reserved variable that returns the current command being executed; in our case, $0 contains the absolute path of the .command file itself. The dirname utility then takes that path and returns the absolute path of the directory containing the .command file. Putting the dirname command in backquotes (`, not to be confused with the normal single quote character ') executes dirname and substitutes its output into the current command line, allowing it to become the argument to the cd command. So in English, what we get is essentially: "Change to the directory containing this file."

Script code executed after this can use relative pathnames that will work regardless of where the .command file is located, with one caveat that I know of: the path to the .command file cannot contain spaces, single-quotes, or other characters that have special meaning to the shell. If anyone knows of a nice, elegant workaround for this, I'd be interested to hear it.

Comments (7)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20041217111834902