Super User is a question and answer site for computer enthusiasts and power users. 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 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 – Raystafarian Apr 1 '12 at 14:44
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

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

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .