Location independent includes

While you're developing scripts, you may come across the need to include other files in your BASH scripts, for code reuse or better organization. Regardless of the reason, being able to include them from the same path of your script without hardcoding paths is actually useful. Here's how to do it:

Step one, you need to determine the full path of your script.

FULLPATH=$(readlink -f $0)


As you should know, the $0 retrives the script name from the parameters. Then, the "readlink -f" is there to obtain the canonical name of the script, ie, the full pathname of it. And, of course, the "$(...)" are there to capture the output of the "readlink" command into the FULLPATH variable.


Step two, you need to extract the path and discard the script name. Here's how:

INCFOLDER=${FULLPATH%/*}


The "${FULLPATH%/*}" actually does the magic of extracting the relevant path elements and discarding the last path element (which is the script file name).


So, there. Now you have the INCFOLDER variable with the path you wanted and you can include your other files just by doing this:


. $INCPATH/file_to_include.sh


There is a less functional alternative which is to use a relative path. However, this alternative has a problem. If you try to call your script from the $PATH, you will be unable to refer to the includes:


RELPATH="${0%/*}"
INCFOLDER=${FULLPATH%/*}


This works, however, if you only use absolute or relative paths, instead of calling it from the command $PATH.