I'm a longtime Windows and Linux user and have had some weird experiences writing shell scripts on Mac OS X. In particular, I can write the scripts just fine and run them from the terminal, but every time I try running one from a Finder window it always executes from the user's home directory rather than the directory in which the script lives. That is, if the script is located at
~/path/to/the/script.sh
it always runs out of ~
. In the past I've had to ask my more Mac-savvy friends how to fix this, and they've often done so using some perversely awful techniques, but I don't see any reason why this should be the case.
My question is - is there an easy way to write a shell script in Mac OS X that, when double-clicked in Finder, runs out of the directory in which it resides?
The behaviour seems consistent to me. It inherits your finder instances environment, which would be rooted at your home directory.
However, it's not too hard to fix.
cd "$(dirname "$0")"
Ought to do the trick ala:
richh-desktop % fullname.sh
/home/richh/bin
richh-desktop % cd ..
richh-desktop % fullname.sh
/home/richh/bin
richh-desktop %
If you want the script to run out of the directory it lives in, the script will have to change its working directory. Given that your example is written in bash, I'll respond with a bash example. The $_ value is set to the absolute path of the current script. You can find more information by running man bash
#!/bin/bash
PROGPATH=$(dirname $_)
cd $PROGPATH
# Do your stuff here
It's going to be up to the script to change the directory for you. Check this page out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With