Shell脚本参数替换

时间:2010-08-11 12:55:12

标签: shell variables parameters

有人能告诉我这两个约定在获取当前正在运行的脚本名称方面有何不同?

#!/bin/sh

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

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

谢谢!

2 个答案:

答案 0 :(得分:2)

你的猜测是正确的。来自我机器上的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.

答案 1 :(得分:1)

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