Gary Gary - 2 months ago 5x
Bash Question

How can a bash script know the directory it is installed in when it is sourced with . operator?

What I'd like to do is to include settings from a file into my current interactive bash shell like this:

$ . /path/to/some/dir/.settings

The problem is that the .settings script also needs to use the "." operator to include other files like this:

. .extra_settings

How do I reference the relative path for .extra_settings in the .settings file? These two files are always stored in the same directory, but the path to this directory will be different depending on where these files were installed.

The operator always knows the /path/to/some/dir/ as shown above. How can the .settings file know the directory where it is installed? I would rather not have an install process that records the name of the installed directory.


I believe $(dirname "$BASH_SOURCE") will do what you want, as long as the file you are sourcing is not a symlink.

If the file you are sourcing may be a symlink, you can do something like the following to get the true directory:

progname=`basename "$BASH_SOURCE"`

while [ -h "$PRG" ] ; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
        PRG=`dirname "$PRG"`"/$link"

dir=$(dirname "$PRG")