In a bash script collection, how do I best include some self-crafted
library functionality defined in the library file "mylibrary"?
I could certainy just source the library file through its absolute path,
but that would break things if the script collection (together with its
library file(s)) is _moved_ to another location.
To work around that, I could use a path relative to my script(s), e.g.
(assuming the library file is one directory above the script's directory):
source "$(dirname "$0")/../mylibrary"
But this still breaks if any of the scripts are sourced themselves by
another script, as "$0" would then expand to that other script. The
following would fix that:
source "$(dirname "${BASH_SOURCE[0]}")/../mylibrary"
But again, this fails if I call the script through a symbolic link
located in some other directory. To also fix that, I'd need to make it
even more complex:
source "$(dirname "$(realpath "${BASH_SOURCE[0]}")")/../mylibrary"
That's quite some overhead required to just reliably make some library
functionality availabe that is typically intended to _ease_ writing scripts.
As I assume that currently, there is no easier way when reliability and
flexibility matters, I'd like to suggest adding a new predefined bash
variable, e.g. named BASH_SCRIPTDIR, that's being assigned the value
"$(dirname "$(realpath "${BASH_SOURCE[0]}")")". Again looking at the
case pointed out above, this would allow to simply souce my bash snippet by:
source "$BASH_SCRIPTDIR/../mylibrary"
What do you think?