Linux Shell Variables

In this tutorial, we are going to discuss about Linux Shell Variables with examples.

A variable is a character string to which we assign a value. The value assigned could be a number, text, filename, device, or any other type of data.

A variable is nothing more than a pointer to the actual data. The shell enables you to create, assign, and delete variables.

Variables are case-sensitive.

Variables are two types:
1. Local Variables: Local variables are only available in the current shell.
2. Global Variables: Global variables or environment variables are available in all shells.

Variable Names
The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or the underscore character(_). By convention, Unix shell variables will have their names in UPPERCASE.

Valid variable names are:

VAR1 _VAR2 VAR_10 _VAR100_

Invalid variable names are:

1_VAR1 -VAR2 !VAR3 VAR-VAR100

Define Variables:

VAR='r2schools' VAR1=100

The above examples defines variable VAR and assigns the value ‘r2schools’ and VAR1 assigns values 100. Variables of this type are called scalar variables. A scalar variable can hold only one value at a time.

Accessing variables:

To access the value stored in a variable, we have to prefix variable name with the dollar sign ($).

root@mongodb1:/home/r2schools/scripts# VAR='r2schools' root@mongodb1:/home/r2schools/scripts# VAR1=100 root@mongodb1:/home/r2schools/scripts# echo $VAR r2schools root@mongodb1:/home/r2schools/scripts# echo $VAR1 100

Unsetting Variables

Unsetting or deleting a variable directs the shell to remove the variable from the list of variables that it tracks. Once you unset a variable, you cannot access the stored value in the variable.

Following is the syntax to unset a defined variable using the unset command −

root@mongodb1:/home/r2schools/scripts# unset VAR root@mongodb1:/home/r2schools/scripts# echo $VAR root@mongodb1:/home/r2schools/scripts#