在bash中带有变量,大括号和哈希字符的$ {0 ## ...}语法是什么意思?

问题描述 投票:34回答:3

我刚看到bash中的一些代码,我不太明白。作为新手bash脚本,我不知道发生了什么。

echo ${0##/*}
echo ${0}

我没有看到这两个命令的输出有什么不同(打印脚本名称)。这是#只是一个评论?和/*有什么关系。如果是评论,为什么它不会干扰关闭}括号?

谁能让我对这种语法有所了解?

bash variables syntax curly-braces
3个回答
48
投票

请参阅Advanced Bash-Scripting Guide中的Substring removal部分:

${string#substring}

substring前面删除$string的最短匹配。

${string##substring}

substring前面删除$string最长的比赛。

子串可以包括通配符*,匹配所有内容。表达式${0##/*}打印$0的值,除非它以正斜杠开头,在这种情况下它不打印任何内容。

‡该指南,截至197年7月7日,错误地声称匹配是$substring,好像substring是一个变量的名称。它不是:substring只是一种模式。


24
投票

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

0
投票

请参阅Parameter Expansion手册页的bash(1)部分。

© www.soinside.com 2019 - 2024. All rights reserved.