Variable Mangling in bash with String Operators
Abstract
Have you ever wanted to change the names of many files at once? How about using a default value for a variable if it has no value? These and many other options are available to you through string operators in bash and other Bourne shell derived shells.
String operators allow you to manipulate the contents of a variable without having to write your own shell functions to do so. They're provided through "curly brace" syntax. Any variable can be displayed like ${foo} without changing its meaning. This functionality is often used to protect a variable name from surrounding characters:
bash-2.02$ export foo=foo bash-2.02$ echo ${foo}bar # foo exists so this works foobar bash-2.02$ echo $foobar # foobar doesn't exist, so this fails bash-2.02$
By the end of this article, you'll be able to use it for a whole lot more.
There are three kinds of variable substitution:
Pattern matching
Substitution
Command substitution
I'll talk about the first two and leave command substitution for another article.