Bash Shell Scripting/Variables

In a Bash script, there are a few different kinds of parameters that can hold values. One major kind of parameter is variables: named parameters. If you are familiar with almost any other imperative programming language (such as C, BASIC, Fortran, or Pascal), then you are already familiar with variables. The following simple script uses the variable  to hold the value , and prints out a "Hello, world!" message:

As you can see, the string  in the second line was replaced by   before that command was run. This substitution is known as variable expansion.

Variable expansion is more flexible than you might suspect. For example, it can even hold the name of the command to run:

In both of the above examples, we have used the notation  to perform the variable expansion. The briefer notation  − without curly brackets − would have the same effect in these cases. Sometimes the curly brackets are necessary (for example,  cannot be written as , because the latter would be interpreted as  ), but they can usually be omitted, and real-world scripts usually omit them.

Of course, needless to say, the above are not very realistic examples; they demonstrate only how to use variables, not why or when to use them. If you are familiar with other imperative programming languages, then it is probably already obvious to you why and when you would use variables; if not, then this should become clear as you read through this book and see examples that use them more realistically.

You may have noticed that we have used double-quotes, rather than single-quotes  , for character-strings that include variable expansions. This is because single-quotes prevent variable expansion; a command such as  will print the actual string , rather than printing the value of a variable named.

It is generally a good idea to wrap variable expansions in double-quotes, because otherwise the results of variable expansion will undergo filename expansion, as well as word splitting (whereby white-space is used to separate the words that make up a command). For example, this script:

is liable to print something like, which is probably not what we want. Real-world scripts frequently do not include double-quotes except when they are clearly necessary, but this practice sometimes leads to confusing bugs.

A number of variables have special significance. For example, the variable  determines the list of directories that Bash should search in when trying to run an external program; if it is set to , then the command   will look to run either   or. The variable  is pre-initialized to the current user's home directory, and it determines the behavior of tilde-expansion. For example, if a script sets, then   will print. (This will not actually change the user's home directory, however.)