How can I get the current script name of a script running in parent script's shell?

Issue

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?

Solution

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

Answered By – ichramm

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published