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

风流意气都作罢 提交于 2019-11-26 12:06:41

问题


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?


回答1:


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.




回答2:


Linux tip: Bash parameters and parameter expansions

${PARAMETER##WORD}  Results in removal of the longest matching pattern from the beginning rather than the shortest.
for example
[ian@pinguino ~]$ x="a1 b1 c2 d2"
[ian@pinguino ~]$ echo ${x#*1}
b1 c2 d2
[ian@pinguino ~]$ echo ${x##*1}
c2 d2
[ian@pinguino ~]$ echo ${x%1*}
a1 b
[ian@pinguino ~]$ echo ${x%%1*}
a
[ian@pinguino ~]$ echo ${x/1/3}
a3 b1 c2 d2
[ian@pinguino ~]$ echo ${x//1/3}
a3 b3 c2 d2
[ian@pinguino ~]$ echo ${x//?1/z3}
z3 z3 c2 d2



回答3:


See the Parameter Expansion section of the bash(1) man page.



来源:https://stackoverflow.com/questions/2059794/what-is-the-meaning-of-the-0-syntax-with-variable-braces-and-hash-chara

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!