我怎么用bash shell参数展开这个表达式?

时间:2012-06-28 07:21:00

标签: bash shell parameters expansion

我今天遇到了一个bash脚本,它有以下主要内容:

$ cat -n deploy.sh
 1  #!/bin/bash
 2   
 3  # Usage: ./deploy.sh [host]
 4   
 5  host="${1:-ubuntu@example.com}"
 6   
 7  # The host key might change when we instantiate a new VM, so
 8  # we remove (-R) the old host key from known_hosts
 9  ssh-keygen -R "${host#*@}" 2> /dev/null
 [...]

第5行很容易。 第9行找到了我。我“相信”它是一种bash参数扩展,但阅读手册页,我不再那么肯定了。

引用bash手册页:

${parameter#word}
${parameter##word}
          Remove matching prefix pattern.  The word is expanded to produce
          a pattern just as in pathname expansion.  If the pattern matches
          the  beginning of the 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 pat‐
          tern (the ``##'' case) deleted.  If parameter is  @  or  *,  the
          pattern  removal operation is applied to each positional parame‐
          ter in turn, and the expansion is the resultant list.  If param‐
          eter  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.

让我说我只是像这样运行脚本

./deploy.sh

没有任何输入参数,然后第5行,主机将设置为ubuntu@example.com。然后来到第9行,$ {host#* @}开始发挥作用。 #使用展开的* @触发替换。但是它扩展到了什么?这不是手册页中使用的单词吗?

任何提示/提示都表示赞赏。

扎克

2 个答案:

答案 0 :(得分:2)

在这个脚本中,“* @”实际上是一个glob模式,而不是任何类型的特殊参数。

$ host="${1:-ubuntu@example.com}"; echo "${host#*@}"
example.com

此构造的作用是在与 host 的值匹配时删除glob的最短匹配前缀。最终结果是域名,因为glob匹配字符串中的所有内容,直到(包括)at符号。

答案 1 :(得分:0)

它删除了与主机中的模式* @匹配的前缀(所以* @扩展为ubuntu @)。例如,ubuntu@example.com成为example.com,即域名。