How can I determine the name of the Bash script file inside the script itself?
Like if my script is in file runme.sh
, then how would I make it to display "You are running runme.sh" message without hardcoding that?
How can I determine the name of the Bash script file inside the script itself?
Like if my script is in file runme.sh
, then how would I make it to display "You are running runme.sh" message without hardcoding that?
To answer Chris Conway, on Linux (at least) you would do this:
readlink prints out the value of a symbolic link. If it isn't a symbolic link, it prints the file name. -n tells it to not print a newline. -f tells it to follow the link completely (if a symbolic link was a link to another link, it would resolve that one as well).
I've found this line to always work, regardless of whether the file is being sourced or run as a script.
If you want to follow symlinks use
readlink
on the path you get above, recursively or non-recursively.The reason the one-liner works is explained by the use of the
BASH_SOURCE
environment variable and its associateFUNCNAME
.[Source: Bash manual]
These answers are correct for the cases they state but there is a still a problem if you run the script from another script using the 'source' keyword (so that it runs in the same shell). In this case, you get the $0 of the calling script. And in this case, I don't think it is possible to get the name of the script itself.
This is an edge case and should not be taken TOO seriously. If you run the script from another script directly (without 'source'), using $0 will work.
$BASH_SOURCE
gives the correct answer when sourcing the script.This however includes the path so to get the scripts filename only, use:
I got the above from another Stack Overflow question, Can a Bash script tell what directory it's stored in?, but I think it's useful for this topic as well.