1

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?

DonGiovanni
  • 891
  • 1
  • 7
  • 15
  • I don't really agree that this is a duplicate question. Yes, the question is how to get the source directory, which is answered in the referred question. However, as far as I saw, they use either `$0` or `${BASH_SOURCE[0]}` in all the answers, which both don't work for my case. So my question is not actually answered in the referred question. – DonGiovanni Sep 02 '18 at 10:48
  • I changed the title to better describe the actual question. – DonGiovanni Sep 10 '18 at 07:44

1 Answers1

0

I just found out that ${BASH_SOURCE[0]:-$0} resolves to the correct script name in both cases.

DonGiovanni
  • 891
  • 1
  • 7
  • 15