Linux bash program (1)

1. Define an environment variable

$ case='D002mm'

The previous command defines a environment variable named "case", which value is "D002mm". You must note: firstly, there is no space in both side of the equal symbol; secondly, if the value is more than an ASCII symbol, you should add the quotes to the value; thirdly,while we can generally use double quotes instead of single quotes, doing it like the above example would have caused an error. Because using single quotes disables a bash feature named expansion, where special characters and sequences of characters are replaced with values.

Let's take a look at how to use environment variables.

$ echo $case
D002mm

By preceding the name of our variable with a $, we can cause bash to replace it with the value of case. In bash terminology, this is called "variable expansion". But, what if we try the following:

$ echo abc$casebush
abc

We wanted this to echo "abccasebush", but it didn't work. What 's wrong? In a nutshell, bash's variable expansion facility in got confused. It couldn't tell whether we wanted to expand the variable $ca, $case, $casebush, etc. How can we be more explicit and clearly tell bash what variable we are referring to? Try this:

$ echo abc${case}bush
abccasebush

As you can see, we can enclose the environment variable name in curly braces when it is not clearly separated from the surrounding text. While $case is faster to type and will work most of the time, ${case} can be parsed correctly in almost any situation. Other than that, they both do the same thing, and you will see both forms of variable expansion in the rest of this series. You'll want to remember to use the more explicit curly-brace form when your environment variable is not isolated from the surrounding text by whitespace (spaces or tabs).

   Send article as PDF   

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.