Discussion:
[Help-bash] Interpreting BASH_SOURCE after changing working folder
João Eiras
2018-04-24 15:09:51 UTC
Permalink
So, consider this simple example:

$ cat example_script.
echo PWD:$PWD
echo BASH_SOURCE:${BASH_SOURCE[@]}
cd /tmp
echo PWD:$PWD
echo BASH_SOURCE:${BASH_SOURCE[@]}
$ bash example_script.sh
PWD:/home/.../
BASH_SOURCE:example_script.sh
PWD:/tmp
BASH_SOURCE:example_script.sh

This shows that BASH_SOURCE includes the exact path used to invoke a
script, whether it was absolute or relative. And in case there was a
change in working folder, the values in BASH_SOURCE no longer match to
a file that can be found in the current folder.

In my use case, I'm coding libraries for testing, logging and
utilities which are quite agnostic to how the program in which they
are sourced is invoked, so any access to BASH_SOURCE needs to be
localized, without artifacts elsewhere to store the original PWD, for
instance.

The question is: how can I get the original PWD when the script was
invoked to help interpret BASH_SOURCE ?

Thank you !

Loading...