Bash programming/Variables

Variables in Bash Scripts are untyped and declared on definition. Bash also supports some basic type declaration using the  option, and bash variables are case sensitive.

Example declaration
The following example script defines and uses a variable named  to print "Hello world.": In this example the variable is referenced using brace expansion

As you can see, you do not need to declare the variable or its type before defining it. In fact, neither are supported in Bash Scripting.

To set a variable, you simply write the name of the variable, in this case "HELLO", immediately follow it with an equal sign, and immediately follow that with whatever data you want to set it to. There cannot be a space between the variable name and the equal sign, nor can there be a space after the equal sign. That is, the following variable definitions will not set the variable correctly:

To use a variable, you simply preceed it with a dollar sign ($). For example, to use the variable FILENAME, you could write: which, after substitution, would simply run the command:

Another way to reference variables in Bash Scripts is by using the dollar sign and enclosing it in curly-braces ({}), called brace expansion. The preceeding example would then be:

This is the preferred way of referencing variables in Bash Scripts, since it explicitly defines the limit of the variable name. To see where these braces are crucial, consider the following example where you want to rename a file named "temp.log" to "temp.log2":

This script would not accomplish your goal of renaming the file, since the interpreter would not understand that the second argument to the cp command was intended to be $FILENAME followed by a 2. Instead, it would try to replace it with a variable named $FILENAME2.

Using the preferred method of referencing, this is not a problem. The preceeding example would now be:

Which would indeed accomplish your goal of renaming the file.

Also note that variable names do not have to be upper-case. Although this convention is quite popular, it is not necessary. Also remember that variables are, however, case-sensitive.

You can also read additional information about how to concatenate variables.

Readings

 * | Bash Guide for Beginners - 3.2 Variables
 * Advanced Bash-Scripting Guide: Chapter 4. Introduction to Variables and Parameters