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:
SCRIPT_NAME="${0##*/}" SCRIPT_DIR="${0%/*}" # if the script was started from the base directory, then the # expansion returns a period if test "$SCRIPT_DIR" == "." ; then SCRIPT_DIR="$PWD" # 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 SCRIPT_DIR="$PWD/$SCRIPT_DIR" fi # now we can source our other scripts source $SCRIPT_DIR/logger.sh