How to get shellscript file name without $ 0?

I tried using python practice if __name__ == "__main__": in shellscript.

Examples of scripts are as follows:

a.sh:

 #!/bin/bash filename="a.sh" function main() { echo "start from $0" echo "a.sh is called" source b.sh bfunc } [[ "$0" == "${filename}" ]] && main 

b.sh:

 #!/bin/bash filename="b.sh" function main() { echo "start from $0" echo "b.sh is called" } function bfunc() { echo "hello bfunc" } [[ "$0" == "${filename}" ]] && main 

You can call it with bash a.sh

If you call bash a.sh , you will get the following:

 start from a.sh a.sh is called hello bfunc 

Here is my question. How can I get the file name without using $0 ? I do not want to write the file name directly, i.e. I want to pass the value of the file name ${filename} .

See the link if you don't know what is the above python practice: What if __name__ == "__ main __": do?

How can I verify that wheather b.sh launched from the command line or was executed by including from a.sh ?

+7
python bash shell
source share
1 answer

You can use the $BASH_SOURCE variable to get the name of the current script file.

 if [[ "$0" == "$BASH_SOURCE" ]] then : "Execute only if started from current script" else : "Execute when included in another script" fi 
+7
source share

All Articles