Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

${0##*/}
${0%/*}

How do they work?

share|improve this question

1 Answer 1

up vote 21 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
2  
So... they didn't want to use basename and dirname? :D –  Aaron D. Marasco Oct 11 '11 at 1:24
6  
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
1  
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
    
True, I was thinking that when I wrote it... but everybody who reads it knows WTF you're up to. ;) –  Aaron D. Marasco Oct 12 '11 at 1:24

Your Answer

 
discard

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.