This needs to resolve symbolic links otherwise path will be that of the
symbolic link rather than that of the actual script file:
There are already ways to safely allow sourcing libraries relative to a
bash script installation without adding features to Bash:
# Create tests and library folders
mkdir -p ./tests/libs
# Create main bash script command
cat > ./tests/real_bash_source_dir_test <<'BASH'
#!/usr/bin/env bash
real_source=$(realpath "${BASH_SOURCE[0]}")
real_source_dir=${real_source%/*}
include_path=$real_source_dir/libs
# shellcheck source=./libs/testlib.bash
source "$include_path/testlib.bash" || exit 1 # cannot load library
TestLib::hello
BASH
# Make it executable
chmod +x ./tests/real_bash_source_dir_test
# Create symbolic link to executable
ln -frs ./tests/real_bash_source_dir_test ./
# Create the library
cat > ./tests/libs/testlib.bash <<'BASH'
(return 0 2>/dev/null) && [ -n "${BASH_VERSION}" ] || exit 1
TestLib::hello() { printf 'Hello from TestLib\n';}
BASH
# Run command script from its real install dir
./tests/real_bash_source_dir_test
# Run command script from its symbolic link in current dir
./real_bash_source_dir_test
You can see it is able to source its library relative to its real
installed path and it works regardless of if called from a symbolic link
or directly from its installed dir.
--
Léa Gris