0

How can I get the name of a child script that is running in the shell of it's parent?

consider script1.sh;

#this is script 1
echo "$0"
. ./script2.sh

and script2.sh;

#this is script 2
echo "$0"

Since script2.sh is being executed in [sourced from] the same shell as script1.sh, the output of running these scripts are both;

./script1.sh

How can get the name of script2.sh within script2.sh?

1

1 Answer 1

2

You are sourcing a script, not running it. Therefore, you are looking for BASH_SOURCE.

$ cat test.sh 
echo $BASH_SOURCE

$ . ./test.sh 
./test.sh

Update:

Some people posted that BASH_SOURCE is indeed an array and, while this is actually true, I don't think you need to use all the syntax boilerplate because. "$BASH_SOURCE" (yes, you should quote your variables) will return the first element of the array, exactly what you are looking for.

Said that, it would be useful to post and example of using BASH_SOURCE as an array so here it goes:

$ cat parent.sh 
#!/bin/bash

. ./child.sh

$ cat child.sh 
#!/bin/bash

. ./grandchild.sh

$ cat grandchild.sh 
#/bin/bash

echo "BASH_SOURCE: $BASH_SOURCE"
echo "child      : ${BASH_SOURCE[0]}"
echo "parent1    : ${BASH_SOURCE[1]}"
echo "parent2    : ${BASH_SOURCE[2]}"

$ ./parent.sh 
BASH_SOURCE: ./grandchild.sh
child      : ./grandchild.sh
parent1    : ./child.sh
parent2    : ./parent.sh

Sign up to request clarification or add additional context in comments.

5 Comments

Don't forget to quote your variables! Also, since BASH_SOURCE is an array, it's clearer to explicitly get the first element. So, echo "${BASH_SOURCE[0]}"
BASH_SOURCE is an array. In the OP scenario, BASH_SOURCE[0] is script2 and BASH_SOURCE[1] is script1.
@ichramm @ wjandrea @glennjackman Thank all three of you for your insight! I just figured I'd add something for anybody viewing this in the future. BASH_SOURCE is reversed-indexed(?), meaning that BASH_SOURCE[0] always refers to the explicit script it's referenced in. BASH_SOURCE[1] refers to the parent script and so on. This is a good thing and exacty what I needed.
@glennjackman @wjandrea BASH_SOURCE can behave an array on an scalar depending on how you use it. $BASH_SOURCE (without brace expansion) will return only the first element of the array.
And did you know that scalars can give you their zero'th element? echo ${HOME[0]}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.