Bash programming/Variables

From Wikiversity
Jump to navigation Jump to search

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

Example declaration[edit | edit source]

The following example script defines and uses a variable named HELLO to print "Hello world.":

HELLO="Hello world."
echo ${HELLO}

In this example the variable is referenced using brace expansion[3][4][5]

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:

VAR1 = "This will not work because there are spaces..."
VAR2= "... neither will this..."
VAR3 ="... nor this."

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:

cp temp.log ~/backup/temp.log

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

cp ${FILENAME} ~/backup/${FILENAME}

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.[7]

Readings[edit | edit source]

References[edit | edit source]