【问题标题】:How do I bash shell parameter expand this expression?如何 bash shell 参数扩展此表达式?
【发布时间】:2012-06-28 07:20:59
【问题描述】:

我今天遇到了一个 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 行,host 将被设置为 ubuntu@example.com。然后来到第 9 行,${host#*@} 开始发挥作用。 # 使用扩展的 *@ 触发替换。但它扩展到什么?这不是手册页中使用的词吗?

感谢任何提示/提示。

扎克

【问题讨论】:

  • 尝试添加echo "${host#*@}"

标签: bash shell parameters expansion


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-16
      • 1970-01-01
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多