Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I encountered this cryptic bit of code which I believe contains some form of variable expansion.

echo "Usage: ${0##*/} [-f] [-u user] [--] "

Is the dollar sign followed by the brace-enclosed string equivalent to the bash variable $0? If so, why would one use the former as opposed to the latter? Thanks for any enlightenment.

share|improve this question
    
This might get a better response on stackoverflow.com –  Raystafarian Apr 1 '12 at 14:44
add comment

2 Answers

up vote 2 down vote accepted

${variable} is regular parameter expansion. The braces can be used to delimit a variable name when expanding in the middle of another string. For example, if you wanted to expand $variablefoo, the shell would have no way to know where the variable name ends. By using ${variable}foo instead, the shell knows exactly what you mean.

The braces also allow for a various other operations to be made during expansion. Your example above deletes what the expression matches, from the left. If given a string such as a path /a/b/c, it will return c. This is effectively equivalent to what basename does, but parameter expansion can be more convenient and readable in some situations.

There are various basic string operations that can be performed with parameter expansion. Being a built in operation, they are generally better performing than sed or awk when doing simple tasks.

If you are into shell scripting, I suggest you read this guide on the bash hackers wiki.

share|improve this answer
    
Good explanation mkaito. Here's a couple links that also explain it well, each in their own style. The "Chopping strings like a pro" section here link and of course The Linux Documentation Project website link –  cdaaawg Apr 3 '12 at 20:11
add comment

It uses parameter expansion to strip the directory from $0.

share|improve this answer
add comment

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.