I just saw some code in bash that I didn't quite understand. Being the newbie bash scripter, I'm not sure what's going on.
echo ${0##/*} echo ${0}
I don't really see a difference in output in these two commands (prints the script name). Is that #
just a comment? And what's with the /*
. If it is a comment, how come it doesn't interfere with the closing }
brace?
Can anyone give me some insight into this syntax?
${0} is the first argument of the script, i.e. the script name or path. If you launch your script as path/to/script.sh , then ${0} will be exactly that string: path/to/script.sh . The %/* part modifies the value of ${0} . It means: take all characters until / followed by a file name.
It finds the name of the script being run, stripping out its directory. For instance if the script is /etc/init. d/httpd then this would set SCRIPTNAME=httpd . $0 , or ${0} , is the name of the script being executed.
If the $0 special variable is used within a Bash script, it can be used to print its name and if it is used directly within the terminal, it can be used to display the name of the current shell.
$0 expands to the name of the shell or shell script. This is set at shell initialization. If bash is invoked with a file of commands, $0 is set to the name of that file.
See the section on Substring removal in the Advanced Bash-Scripting Guide‡:
${string#substring}
Deletes shortest match of
substring
from front of$string
.${string##substring}
Deletes longest match of
substring
from front of$string
.
The substring may include a wildcard *
, matching everything. The expression ${0##/*}
prints the value of $0
unless it starts with a forward slash, in which case it prints nothing.
‡ The guide, as of 3/7/2019, mistakenly claims that the match is of $substring
, as if substring
was the name of a variable. It's not: substring
is just a pattern.
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