Bash 中的 `${1#*=}` 是什么意思?

What does `${1#*=}` mean in Bash?

我发现了一个很棒的 answer on Whosebug which explains how to pass an associative array to a function. Would someone be able to help me figuring out what the syntax of ${1#*=} in the code below specifies? (Borrowed from that answer by jaypal singh):

#!/bin/bash

declare -A weapons=(
  ['Straight Sword']=75
  ['Tainted Dagger']=54
  ['Imperial Sword']=90
  ['Edged Shuriken']=25
)

function print_array {
    eval "declare -A arg_array="${1#*=}
    for i in "${!arg_array[@]}"; do
       printf "%s\t%s\n" "$i ==> ${arg_array[$i]}"
    done
}

print_array "$(declare -p weapons)"

这是我目前的猜测(如果我有任何错误请纠正我):
- 1表示传递给函数的第一个参数(</code>或<code>
- # 表示 </code> 的索引,因为 <code> 是一个 关联 数组,所以 # 成为 [= 的键14=]
- * 表示关联数组 </code></p> 中 <code># 键的值

剩下 =。这意味着什么?这是不是表明您希望 #* 表示关联数组的键和值的一种方式?

片段${1#*=}与关联数组无关。*(Bash的语法非常一致,一点也不混乱)

这是对您的函数或脚本的第一个参数 (</code>) 值的模式匹配。它的语法是</p> <pre><code>${variable#glob}

哪里

  • variable 是任何 bash 变量
  • glob 是要匹配的任何 glob 模式(以 路径名扩展 为准)

它删除最短的匹配项,从行首开始。 还有##删除从变量开头开始的最长匹配,%删除从结尾开始的最短匹配,%%删除从变量开始的最长匹配从头开始。


所以,例如下面的代码:

myVar="abc=llamas&disclaimer=true"
echo "${myVar#*=}"

将在屏幕上打印 llamas&disclaimer=true

另一方面,

myVar="abc=llamas&disclaimer=true"
echo ${myVar##*=}

将打印 true,并且

myVar="foobar is bad"
echo "${myVar%%b*}"

将打印 foo


* 这在bash man page中有充分的解释;只需搜索字符串 ${parameter#word} 即可找到它

它删除由 </code>.</p> 评估的字符串中由模式 <code>*= 匹配的字符串(从开始的最短匹配)

</code>是第一个<a href="http://www.gnu.org/software/bash/manual/html_node/Shell-Parameters.html#Shell-Parameters" rel="nofollow">positional parameter</a>传递给shell.</p> <p>一般格式也可以写成<code>${var#patt},其中patt$var中匹配(最短匹配)并删除。

示例:

var="first=middle=last"
echo "${var#*=}"

输出:

middle=last

如果使用 ## 而不是 #${var##pat},则 pat 匹配最长的匹配项(从开始)。

示例:

var="first=middle=last"
echo "${var##*=}"

输出:

last


From Bash Manual:

${parameter#word}

${parameter##word}

The word is expanded to produce a pattern just as in filename expansion (see Filename Expansion). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘#’ case) or the longest matching pattern (the ‘##’ case) deleted. If parameter is ‘@’ or ‘’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.