Dec 20, '04 09:04:00AM • Contributed by: davemak
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.
