How to Use Variable in Bash Scripts

As the complexity of a shell script increases, it is often helpful to make use of variables. A variable serves as a container, within which a shell script can store data in memory. Variables make it easy to access and modify the stored data during a script’s execution.

Assigning values to variables

Data is assigned as a value to a variable via the following syntax:

VARIABLENAME=value

While variable names are typically uppercase letters, they can be made up of numbers, letters (uppercase and lowercase), and the underscore character, ‘_’. However, a variable name cannot start with a number. The equal sign, =, is used to assign values to variables and must not be separated from the variable name or the value by spaces. The following are some examples of valid variable declarations.

COUNT=80
first_name=Vicky
file1=/tmp/file01.txt
_ID=AB123

Two common types of data stored in variables are integer values and string values. It is good practice to quote string values when assigning them to variables since the space character is interpreted by Bash as a word separator when not enclosed within single or double-quotes. Whether single or double quotes should be used to enclose variable values depends on how characters with special meanings to Bash should be treated.

full_name='John Doe'
full_name="$FIRST $LAST"
price='$1'

Expanding variable values

The value of a variable can be recalled through a process known as variable expansion by preceding the variable name with a dollar sign, $. For example, the value of the VARIABLENAME variable can be referenced with $VARIABLENAME. The $VARIABLENAME syntax is the simplified version of the brace-quoted form of variable expansion, **${VARIABLENAME}**. While the simplified form is usually acceptable, there are situations where the brace-quoted form must be used to remove ambiguity and avoid unexpected results.

In the following example, without the use of brace quotes, Bash will interpret $FIRST_$LAST as the variable $FIRST_ followed by the variable $LAST, rather than the variables $FIRST and $LAST separated by the ‘_’ character. Therefore, brace quoting must be used for variable expansion to function properly in this scenario.

$ FIRST_=Jane
$ FIRST=John
$ LAST=Doe
$ echo $FIRST_$LAST JaneDoe
$ echo ${FIRST}_$LAST John_Doe