Mental Jetsam

By Peter Finch

Determine a shell scripts home directory.

Posted by pcfinch on June 5, 2008

The following bit of shell script is useful in determining the home directory of the script being run. When a script is executed from the command line normally it’s home directory is the directory that the script was execute from not the directory the script lives in. This can make it difficult to load other
resources that may be in the scripts home directory or relative to it.

DIRNAME=`dirname "$0"`
SCRIPTDIR=`(cd $DIRNAME && pwd)`

2 Responses to “Determine a shell scripts home directory.”

  1. scaryreasoner said

    Interesting… “dirname” returns “.” (on my system) for arbitrary strings which don’t contain ‘/’, which makes this behavior correct.

    The one thing I see to watch out for is that “pwd” is a shell builtin, which does not expand symlink names (e.g. /bin/pwd and pwd will return different results if there is a symlink along the way.)

    In most cases, if your script cares about the absolute path of the directory it’s run from, then your script is, very likely, at least somewhat broken. Or, some app it depends on is somewhat broken.)

  2. I have learn a few just right stuff here. Certainly price bookmarking for revisiting.
    I surprise how a lot attempt you set to make this sort of excellent informative site.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: