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?
If the script name has spaces in it, a more robust way is to use
"$0"
or"$(basename "$0")"
- or on MacOS:"$(basename \"$0\")"
. This prevents the name from getting mangled or interpreted in any way. In general, it is good practice to always double-quote variable names in the shell.In
bash
you can get the script file name using$0
. Generally$1
,$2
etc are to access CLI arguments. Similarly$0
is to access the name which triggers the script(script file name).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.With bash >= 3 the following works:
If you want it without the path then you would use
${0##*/}
$0
doesn't answer the question (as I understand it). A demonstration:How does one get
./linktoscript
to print outscript.sh
?[EDIT] Per @ephemient in comments above, though the symbolic link thing may seem contrived, it is possible to fiddle with
$0
such that it does not represent a filesystem resource. The OP is a bit ambiguous about what he wanted.