代码之家  ›  专栏  ›  技术社区  ›  Buggabill

shell脚本参数替换

  •  3
  • Buggabill  · 技术社区  · 14 年前

    有人能告诉我这两种获取当前运行脚本名称的约定有什么区别吗?

    #!/bin/sh
    
    echo $0
    echo ${0##*/}
    

    第二个版本是否从脚本名中删除路径?

    谢谢!

    2 回复  |  直到 14 年前
        1
  •  2
  •   Greg Hewgill    14 年前

    你的猜测是正确的。从 bash 我机器上的文档:

       ${parameter#word}
       ${parameter##word}
              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 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.
    
        2
  •  1
  •   Sergey Naumov    14 年前

    是的,第二个版本使用bash扩展来剪切与*/regexp匹配的最长前缀$0,所以如果$0是“/bin/bash”,那么$0__*/将是“bash”。您可以使用'basename$0'来获得相同的结果。