Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of the ${0##...} syntax with variable, braces and hash character in bash?

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?

like image 371
user215997 Avatar asked Jan 13 '10 20:01

user215997


People also ask

What is ${ 0 * in shell script?

${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.

What is the purpose of Scriptname?

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.

What is the use of $0?

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.

What is $0 return bash?

$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.


1 Answers

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.

like image 154
Mark Byers Avatar answered Nov 08 '22 01:11

Mark Byers