开发者

Shell script parameter substitution

开发者 https://www.devze.com 2023-01-10 22:17 出处:网络
Can someone tell me what the difference is between these two conventions for getting the name of the currently running script?

Can someone tell me what the difference is between these two conventions for getting the name of the currently running script?

#!/bin/sh

echo $0
echo $开发者_开发百科{0##*/}

Does the second version strip the path from the script name?

Thanks!


Your guess is correct. From the bash docs on my machine:

   ${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.


Yes, second version uses bash extension to cut longest prefix of $0 which match to */ regexp, so if $0 is "/bin/bash", then ${0##*/} will be "bash". You can use `basename $0` to achieve the same result.

0

精彩评论

暂无评论...
验证码 换一张
取 消