Possible Duplicate:
In the bash script how do I know the script file name?
How can you access the base filename of a file you are sourcing in Bash
When using source
to call a bash script from another, I'm unable to find out from within that script what the name of the called script is.
file1.sh
#!/bin/bash
echo "from file1: $0"
source file2.sh
file2.sh
#!/bin/bash
echo "from file2: $0"
Running file1.sh
$ ./file1.sh
from file1: ./file1.sh # expected
from file2: ./file1.sh # was expecting ./file2.sh
Q: How can I retrieve file2.sh
from file2.sh
?
If we prefer not to print the path and only want the name of the script to show, we can use the basename command, which extracts the name from the path.
If you invoke the script with path like /path/to/script.sh then $0 also will give the filename with path. In that case need to use $(basename $0) to get only script file name.
Change file2.sh
to:
#!/bin/bash
echo "from file2: ${BASH_SOURCE[0]}"
Note that BASH_SOURCE
is an array variable. See the Bash man pages for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With