How does a script know its name in bash?

I run script.sh and inside it I want to know his name

Is there a standard procedure to find out the name of a script? the idea is to be able to extract the name from the full path + the name contained in$0

thank

+3
source share
3 answers

Yes, $0it will always contain the name of the script. Use basename to retrieve the name.

basename /some/really/long/dir/path/myscripts/coolscript.sh will print coolscript.sh

So in your script you can do this:

my_scriptname="$(basename $0)"
+6
source
script="${0##*/}"

Edit:

It does the same thing as basename $0. It discards the last slash and everything from it $0with the help of the Bash extension.

+2
source

basename $0 script

+1

Source: https://habr.com/ru/post/1744822/


All Articles