简体   繁体   中英

Shell script parameter substitution

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM