PDA

View Full Version : Referring to the directory that a script is running from?




AquaMethod
Jan 21, 2009, 02:27 PM
I'd like to create a bash script that would live on a USB thumb drive and copy over some files from that same USB drive, onto the Mac it's plugged into. How can I refer to the path the script is executing from, even if the name of the drive has changed or it's not mounted under /Volumes ?

I suppose it's possible to mess around with the $0 parameter, but will that work even if the script is created as a .command file, and run by the Finder?



mkrishnan
Jan 21, 2009, 02:31 PM
It doesn't matter how the script is executed -- dirname should work (pwd may not). See:

http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-in

AquaMethod
Jan 23, 2009, 06:20 PM
Ah, that makes sense. (Not sure why I didn't think to search SO first...thanks for doing so)

So the cleanest solution would probably be

scriptPath=`dirname $0`

And then use $scriptPath from there one? Seems like that'll work.

mkrishnan
Jan 23, 2009, 07:14 PM
Yeah, something like that should work just fine. :)