Keep the variable name safe

We just saw that $label is the way we reference the content of a variable, but if you have a look at some scripts, you can find another way of retrieving variable content:

${label}  

The two ways of referencing the content of a variable are both valid, and you can use the first, more compact, in any case except when concatenating the variable name to any characters, which could change the variable name itself. In this case, it becomes mandatory to use the extended version of the variable substitution, as the following example will make clear.

Let's start printing our variable again:

gzarrelli:~$ echo $FIRST_VARIABLE
amazing

Now, let's do it again using the extended version of substitution:

gzarrelli:~$ echo ${FIRST_VARIABLE}
amazing

Exactly the same output since, as we said, these two methods are equivalent. Now, let us add a string to our variable name:

gzarrelli:~$ echo $FIRST_VARIABLEngly    
gzarrelli:~$

Nothing, and we can understand why the name of the variable changed; so we have no content to access to. But now, let us try the extended way:

gzarrelli:~$ echo ${FIRST_VARIABLE}ly
amazingly

Bingo! The name of the variable has been preserved so that the shell was able to reference its value and then concatenated it to the ly string we added to the name.

Keep this difference in mind, because the graphs will be a handy way to concatenate strings to a variable to spice your scripts up and, as a good rule of thumb, refer to variables using the graphs. This will help you avoid unwanted hindrances.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.162.110