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"


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##*/}
$ basename $x

From the man page:

       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.

  • Just curious, how did you get the man page for this? Aug 2 '18 at 15:08
  • Have you tried man bash and then searched for parameter##?
    – Anthon
    Aug 2 '18 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 '18 at 15:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.