Print the name of the running Bash script
October 24, 2020 ‐ 2 min read
When writing a Bash script you might be wanting to get the file name of the script. For outputting an error message this is useful for example. As is shown below.
$ ls --pizza
ls: unrecognized option '--pizza'
Try 'ls --help' for more information.
The full name of the script is stored in $0
. So the following script would work.
#!/bin/bash
script_name=$0
echo $script_name
$ ./bin/h4ckerman
./bin/h4ckerman
However it gives you the full path as shown above. For me, I am mostly interested in just the file name of the script. This is where basename
comes in. basename
is a shell program available, and it gives you the base name... duh.
#!/bin/bash
script_name=$(basename $0)
echo $script_name
$ ./bin/h4ckerman
h4ckerman
That's more like it.
Another option that produces the same result as above is by using ${0##*/}
. ${0##*/}
makes use of parameter expansion in Bash. With ${0##*/}
you drop the longest substring (match) till the last /
for parameter $0
.
#!/bin/bash
script_name=${0##*/}
echo $script_name
$ ./bin/h4ckerman
h4ckerman
Another option would be to use the $BASH_SOURCE
variable instead of $0
. However, as the name implies, this is functional in Bash and not POSIX compliant. So it wouldn't function per se in a shell that isn't Bash.
But as long you know for sure the script is only to run in Bash, you might as well use it.
Also be aware that $0
stores the name of how the script was called. Which isn't the same as the path of the actual script file, in case the script was symlinked.
In case that matters for your use case you can use the following:
echo $(basename $(readlink -nf $0))
Learning more
The best way to learn more is to use Bash. A lot. Don't forget that Google is your friend.
In case you learn well from books I would recommend these.