1

I am wondering if there is a way to find out how a file execution was initiated.

For example, consider the following files:

~/foo.sh

echo "Hello from foo.sh"
# print the name of the initiator/parent of this execution 

~/bar.sh

source ~/foo.sh

~/baz.sh

. ~/foo.sh

When I execute

sh ~/bar.sh or .~/bar.sh, ~/foo.sh should print ~/bar.sh

sh ~/baz.sh or .~/baz.sh, ~/foo.sh should print ~/baz.sh


I am trying to be generic but it could be specific to bash or zsh.

2 Answers2

1

This is a bash solution (for scripts with #!/bin/bash as the first line, or run with bash script...).

Set up the example (two scripts, a.sh and b.sh):

cat >a.sh <<'x' && chmod a+x a.sh
#!/bin/bash
echo This is a.sh
source b.sh
echo End a.sh
x

cat >b.sh <<'x' && chmod a+x b.sh
#!/bin/bash
echo This is b.sh
echo "BASH_SOURCE=(${BASH_SOURCE[@]}) and we are '${BASH_SOURCE[0]}' called by '${BASH_SOURCE[1]}'"
echo End b.sh
x

Now run the code and review the output:

./a.sh
This is a.sh
This is b.sh
BASH_SOURCE=(b.sh ./a.sh) and we are 'b.sh' called by './a.sh'
End b.sh
End a.sh

As you can see, in a sourced file the caller can be identified with "${BASH_SOURCE[1]}".

Chris Davies
  • 116,213
  • 16
  • 160
  • 287
0

It would be possible with the bash shell. source can supply an argument to the file there.

That means you could construct foo.sh as:

#!/bin/bash
echo "Hello from $1"

and bar.sh as

#!/bin/bash
source ~/Codes/tests/foo.sh '~/bar.sh'

finally baz.sh would look like this:

#!/bin/bash
source ~/Codes/tests/foo.sh '~/baz.sh'

If you care about how the script was invoked, then you could also write foo.sh as

#!/bin/bash
echo "Hello from $0"

and bar.sh as

#!/bin/bash
source ~/Codes/tests/foo.sh

This will give Hello from ./bar.sh if you invoke it from the scripts directory. If you invoke it from your home you will get Hello from ~/bar.sh

Max1
  • 210
  • Thank you Max1! Is there any other way to find out how a script is getting invoked? – Sarbbottam May 01 '20 at 20:45
  • OP says sh not bash, so you cannot assume source permits a second argument. @sarbbottam if you are allowing bash extensions please update your question to say so. – Chris Davies May 01 '20 at 20:45
  • I always use .sh as a file extension for my bash scripts. I wouldn't deduce from that, that its supposed to be sh shell. – Max1 May 01 '20 at 20:48
  • Max1, the OP in their question shows sh a.sh, which is clearly sh rather than bash (the "extension" is irrelevant - it's the command that's vital here). – Chris Davies May 01 '20 at 20:49
  • Sorry, your right I overlooked that. – Max1 May 01 '20 at 20:51
  • Hi Max1, roaima I have updated the question, could you take another look? Thank you! – Sarbbottam May 01 '20 at 21:29