Determining the base directory of a bash script

While writing bash scripts, I find it a good idea to put reusable functions into their own scripts and then source them into other scripts.

This means that one must use the source /file/to/source call to load these files. To be able to do this, the bash script must know where the scripts to source are. To not have to hardwire this into the script, I just have the requirement, that the script must be in the same directory as the script itself.

The following code shows how one can find the base directory, with out using any external commands and it should work with out regards to how the script is called:


# if the script was started from the base directory, then the 
# expansion returns a period
if test "$SCRIPT_DIR" == "." ; then
# if the script was not called with an absolute path, then we need to add the 
# current working directory to the relative path of the script
elif test "${SCRIPT_DIR:0:1}" != "/" ; then

# now we can source our other scripts
source $SCRIPT_DIR/