Le 19/06/2024 à 22:04, Will Allan écrivait :
Since I find the accepted answer to be overly complex for my needs, I
usually just do this:

declare -r SCRIPT_DIR="$(dirname -- "${BASH_SOURCE[0]}")"
source -- "${SCRIPT_DIR}/../lib/foo.sh"
source -- "${SCRIPT_DIR}/../lib/bar.sh"
...

But, I still don’t like it. I have to start off each script with a slow
command substitution (subshell) which introduces a variable that I don’t
  really want, but it’s too slow to do this repeatedly:

source -- "$(dirname -- "${BASH_SOURCE[0]}")/../lib/foo.sh"
source -- "$(dirname -- "${BASH_SOURCE[0]}")/../lib/foo.sh"

Look like you did not find a proper answer there. Here is one simple that involve no sub-shell at all and does exactly what your sub-shell version does.

declare -r SCRIPT_DIR=${BASH_SOURCE[0]%/*}

Now indeed this does not solve symbolic links and to do this, you need a sub-shell and it is not system agnostic anymore.

realSource=$(realpath -- "${BASH_SOURCE[0]}") && realScriptDir=${realSource%/*}




--
Léa Gris

Reply via email to