Sunday, December 11, 2022

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

Issue

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.


Answered By - Mark Byers
Answer Checked By - Cary Denson (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.