Working With Environment Variables in Linux

Before you start

Objectives: Learn what are environment variables, how to see them, how to set new variables, and about some common variables.

Prerequisites: no prerequisites.

Key terms: variables, command, set, new, environment, session, use, terminal


Setting Variables

We can both see and change current variables, and set new environment variables in Linux. To see defined variables we can use the “set” command. In our case we will also use the ” | more”  pager, since the list of all variables is pretty long. So, the whole command is: “set | more“.

 1 set Command

set Command

Another option is to use the “env” command, which will also display all of the environment variables.

 2 env Command

env Command

We can also set our own environment variables. To do that, we simply type the name of the variable, then the equals sign, and then the value of the variable. The name of the variable should be written all caps. In our case we will add a variable “ATEMP=delete”. The name of the variable is ATEMP, and the value is “delete”.

 3 New Variable Set

New Variable

To see if the variable is really there we can use the “set” command again and search for it in the list. We can also echo it. The command to do that is “echo $ATEMP” (we add a $ sign before the name of the variable).

 4 echo Command

echo Command

When we set variable like this, we actually set it only for the current session. If we create a new session, we won’t be able to access our variable. To create a new session we can simply enter “sh” command, and this will create a new bash session in our current terminal window. When we try to echo our ATEMP variable, we won’t get any result. However, notice that the USER variable works. 

 5 New Session

New Session

To make our variables available to child sessions, we first need to export that variable. So, we will exit our new shell, and then use the “export ATEMP” command to export our ATEMP variable to all child sessions.

 6 export Command

export Command

So we can see that our variable is now available to any child session. But, be aware that if we open another terminal window, our variable won’t be available. That’s because the new terminal window is not the child of our original terminal window. So, always keep in mind how variables are inherited. Also, keep in mind that we can also set user-defined variables automatically using a shell script.

Deleting Variables

If we no longer need our variables, we can use the unset command together with the variable name. For example, in our case the command would be “unset ATEMP“.

Common Environment Variables

  • SHELL – current shell’s path.
  • TERM – terminal settings.
  • HOME – absolute path of the user’s home directory.
  • LANG – language of the operating system.
  • PATH – directories used to search for programs and files. Entries are separated with a colon.