2

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.

1
  • This might get a better response on stackoverflow.com Commented Apr 1, 2012 at 14:44

2 Answers 2

3

${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.

1
  • 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 Commented Apr 3, 2012 at 20:11
2

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.