views:

22

answers:

2

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!

A: 

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.

Sergey Naumov
+2  A: 

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.
Greg Hewgill
@Greg Hewgill - Thanks!
Buggabill