Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


How do they work?

share|improve this question
up vote 28 down vote accepted

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.

share|improve this answer
So... they didn't want to use basename and dirname? :D – Aaron D. Marasco Oct 11 '11 at 1:24
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
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
It's not bash-specific, it's specified by POSIX sh. – nyuszika7h Jun 16 '14 at 12:07

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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