I'm quite confused about the following regular expressions I found in a shell script:


How do they work?


Those are not regular expressions, they are examples of Bash's parameter expansion: the substitution of a variable or a special parameter by its value. The Wooledge Wiki has a good explanation.

Basically, in the example you have, ${0##*/} translates as:

for the variable $0, and the pattern '/', the two hashes mean from the beginning of the parameter, delete the longest (or greedy) match—up to and including the pattern.

So, where $0 is the name of a file, eg., $HOME/documents/doc.txt, then the parameter would be expanded as: doc.txt

Similarly, for ${0%/*}, the pattern / is matched against the end of parameter (the %), with the shortest or non-greedy match deleted – which in the example above would give you $HOME/documents.

See also the article on the Bash Hacker's Wiki.

  • 2
    So... they didn't want to use basename and dirname? :D Oct 11 '11 at 1:24
  • 9
    One advantage is that parameter susbstitution doesn't spawn a subprocess...
    – jasonwryan
    Oct 11 '11 at 2:11
  • @jasonwryan,can you elaborate the functionality of * in the above two examples? Or why we have to put * there. In specific, in the first example, * is placed before // ; while in the second example, * is placed after /. What is the underlying difference? Thanks.
    – user785099
    Oct 11 '11 at 3:02
  • 4
    The glob (*) indicates that everything up to and including the pattern will be deleted. Hence, for the beginning of the parameter, #, it is on the left and the end, %, working the other way from the right.
    – jasonwryan
    Oct 11 '11 at 3:06
  • 6
    It's not bash-specific, it's specified by POSIX sh.
    – nyuszika7h
    Jun 16 '14 at 12:07

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.