Synthird's blog

Variables in the Linux terminal

Local variables

Creating one

Creating a local variable is simple by typing:

local_variable_name=value

To create a variable that stores the number one for example, you type:

number_one=1

To make sure a variable is created, you use the echo command and a dollar sign before the name of the variable:

echo $local_variable_name

Going back to our number_one variable, to see if it's created, you type:

echo $number_one

In turn, the terminal should just display the number one:

1

Global variables

Creating one

You create a global variable by typing:

export global_variable_name=value

So to create a global variable storing the number two for example, you type:

export number_two=2

To check if a global variable is created, you use the same process on checking if a local variable is created. That being using the echo command:

echo $global_variable_name

So to check if the variable number_two is created, you type:

echo $number_two

In which, the terminal should just display the number two:

2

Check if a variable is global

To see if a variable is actually global, you type:

env | grep variable_name

So for our number_two variable, you type:

env | grep number_two

In which, the terminal should display:

number_two=2

Predefined global variables

There are also already global variables on your system that you never made. Like HOME and PATH for example. And you can display their values using the echo command.

Displaying the value for the global HOME variable for example:

echo $HOME

Will just display the path of your user folder.

Converting local variables into global ones

You can convert a local variable into a global one by typing:

export local_variable_name

Let's create a local variable called number_three for example:

number_three=3

Of course, running:

echo $number_three

Will cause the terminal to display just the number three:

3

However, running:

env | grep number_three

Won't cause the terminal to display anything since number_three isn't a global variable.

To convert number_three to a global variable, you type:

export number_three

Now when you run:

env | grep number_three

The terminal should display:

number_three=3

Deleting variables

To delete a variable, you type:

unset variable_name

This works regardless if the variable is local or global.

So to delete the variable number_three you made, you type:

unset number_three

Now if you type:

echo $number_three

The number three shouldn't be displayed since the number_three variable got deleted.

And because number_three was a global variable, typing:

env | grep number_three

Will not display anything either.