Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell Scripts in Mac OS X run from home directory?

Tags:

shell

macos

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?

like image 816
templatetypedef Avatar asked Jan 05 '11 02:01

templatetypedef


3 Answers

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 %        
like image 143
richo Avatar answered Oct 02 '22 16:10

richo


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
like image 31
Zac Sprackett Avatar answered Oct 02 '22 16:10

Zac Sprackett


It's going to be up to the script to change the directory for you. Check this page out.

like image 43
Staros Avatar answered Oct 02 '22 15:10

Staros