Search code examples
bashvariablessyntaxcurly-braces

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?


Solution

  • See the section on Substring removal on the parameter expansion page of the bash-hackers' wiki:

    ${PARAMETER#PATTERN} and ${PARAMETER##PATTERN}

    This form is to remove the described pattern trying to match it from the beginning of the string. The operator # will try to remove the shortest text matching the pattern, while ## tries to do it with the longest text matching.

    Example string (just a quote from a big man):

    MYSTRING="Be liberal in what you accept, and conservative in what you send"

    Syntax Result
    ${MYSTRING#*in} Be liberal in what you accept, and conservative in what you send.
    ${MYSTRING##*in} Be liberal in what you accept, and conservative in what you send.