Variables Within the UNIX Shell - The usage of curly braces
(Page 3 of 5 )
There are times when just putting the name of the variable inside a string delimited with the double quote is hard to make clear. Suppose I want to print "redHearth" on the terminal. More than this, I want to get the color of the hearth from a variable. I d not need the space between the two, and due to this, I will use the double quote to bypass the need to add this.
echo "$ColorHearth"
Now the upper solution is what we can come up with; however, inside the quotes, the shell has a hard time figuring out if we wanted the variable "ColorHearth" or the color, and will probably choose the first option. To avoid situations like this, to make this clear and to introduce further opportunities, we use the {}. All we need to do is enclose inside these curly braces the name of the variables as follows:
echo "${Color}Hearth"
We can also make the following basic tests and replaces:
${color:-red}
If the variable does not exist, it will return the string "red" and not assign a value to/create the variable.
${color:=red}
Just like the earlier case above, however, now it will assign the string "red" to the variable and send it back after the string "red."
${color:?No color!}
If the variable does not exist, the shell program / command line will stop with the given error message.