Real path of an included script Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Real path of an included script without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Can an included script know if it’s being included and get its real path ?

Suppose a script called sub.sh that check if the user has access to the script group, before to run its main logic:

#...
mypath=`realpath -e $0`
#if blablabla ... check mypath against user groups...
#
#...

The above script can be included in another one, like so:

#...
. sub.sh
#...

But, as it is being included by another script, the check-up runs against the caller script, which isn’t the desired effect.

Answer

You’re probably looking for the BASH_SOURCE array (in bash).

Example:

sourcee.bs

fun(){
    echo "$0"
    echo "${BASH_SOURCE[0]}"
}

sourcer.bs

#!/usr/bin/env bash
echo "$0"
echo "${BASH_SOURCE[0]}"
source sourcee.bs
fun

testrun

$ ./sourcer.bs
./sourcer.bs
./sourcer.bs
./sourcer.bs
sourcee.bs    #Or the full path if it's in PATH instead of the PWD
We are here to answer your question about Real path of an included script - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji