10

I am trying to understand the variable ${0##*/} that I encountered in a bash script.

I understand that $0 contains the name, or the path, of the script, then ## works as in ${parameter##pattern} (source).

But I don't understand what the / is doing here. I only know this kink of syntax with two slashes:${parameter/pat/string}

When I echo this variable in bash, I get bash :)

Finally, I don't have the authorization to share the script. Let me just say that the variable is called SOFT="${0##*/}" and is used in a printf statement "Error message sent by $SOFT"

1 Answer 1

15

This cuts of all the preceding path elements, just as basename $0 would do. The ## tries to find the longest matching expansion of the prefix pattern:

$ x=/a/b/c/d
$ echo ${x##*/}
d
$ basename $x
d

From the man page:

${parameter##word}
       Remove matching prefix pattern.  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 pat‐
       tern (the ``##'' case) deleted.  

The reason for using ${0##*/} is that it doesn't involve an external program call, but it is kind of obscuring what is going on.

3
  • Just curious, how did you get the man page for this? Aug 2, 2018 at 15:08
  • Have you tried man bash and then searched for parameter##?
    – Anthon
    Aug 2, 2018 at 15:34
  • Yeah, I did do man bash but silly me, I searched for ${ so it failed to find some match. Thanks. Aug 2, 2018 at 15:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .