I have a script, that configures some environment variables. Therefore it needs its own position, the value of $0.
I have another script that sources the first script, but it could also happen that the first script is sourced from the console.
However, neither $0
, nor ${BASH_SOURCE[0]}
seem to work consistently on MacOS. Here is a small example to show what I mean:
a.sh:
#!/bin/bash -eu
source ./b.sh
b.sh:
#!/bin/bash -eu
echo "$0"
echo "${BASH_SOURCE[0]}"
Output of ./a.sh
:
./a.sh
./b.sh
Output of source ./b.sh
:
./b.sh
<empty line, can't get stackoverflow to display it properly>
Not relevant, but just for completeness: output of ./b.sh
:
./b.sh
./b.sh
So, in short: If I use $0
to get the script name, it is wrong when sourced via another script. If I use ${BASH_SOURCE[0]}
, it will be empty when sourced directly.
How can I get the script name in both cases?