Chapter 4. Variable Vernacular
It is not uncommon to see an error message or an assignment statement that contains the idiom ${0##*/}, which looks to be some sort of reference to $0, but something more is going on.
Let’s take a closer look at variable references and what some of these extra characters do for us.
What we’ll find is a whole array of string manipulations that give you quite a bit of power in a few special characters.
Variable Reference
Referencing a variable’s value is very straightforward in most programming languages.
You either just use the name of the variable or add a character to the name to explicitly say that you want to retrieve the value.
That’s true with bash: you assign to the variable by name, VAR=something, and you retrieve the value with a dollar-sign prefix: $VAR.
If you’re wondering why we need the dollar sign, consider that bash deals largely with strings, so:
MSG="Error: FILE not found"
will give you a simple literal string of the four words shown, whereas:
MSG="Error:$FILEnot found"
will replace the $FILE with the value of that variable (which, presumably, would hold the name of the file that it was looking for).
Variable Interpolation
Be sure to use double quotes if you want this string substitution to occur. Using single quotes takes all characters literally, and no substitutions happen.
To avoid confusion over where the variable name ends (the spaces make it easy in this example), a more complete syntax for variable reference uses braces ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access