There is a special bash
variable meant for this,
BASH_SOURCE
An array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are defined. The shell function ${FUNCNAME[$i]} is defined in the file ${BASH_SOURCE[$i]} and called from ${BASH_SOURCE[$i+1]}
It is literally an array variable, that holds a stack trace of sources, where ${BASH_SOURCE[0]}
is the latest one.
An example shamelessly stolen from this-site, just for demonstration purposes,
Script aaa.sh
#!/bin/bash
echo "from ${BASH_SOURCE[0]} : BASH_SOURCE = ${BASH_SOURCE[*]}"
source bbb.sh
Script bbb.sh
#!/bin/bash
echo "from ${BASH_SOURCE[0]} : BASH_SOURCE = ${BASH_SOURCE[*]}"
source ccc.sh
Script ccc.sh
#!/bin/bash
echo "from ${BASH_SOURCE[0]} : BASH_SOURCE = ${BASH_SOURCE[*]}"
for i in ${BASH_SOURCE[@]}; do
readlink -f $i
done
Running aaa.sh
produces,
from aaa.sh : BASH_SOURCE = aaa.sh
from bbb.sh : BASH_SOURCE = bbb.sh aaa.sh
from ccc.sh : BASH_SOURCE = ccc.sh bbb.sh aaa.sh
/tmp/ccc.sh # -> first element showing the latest script sourced
/tmp/bbb.sh
/tmp/aaa.sh