An intro to managing user environment variables

Environment variables control how your working environment in Linux looks, acts, and feels. There are two types of variables:

  • Environment variables: These are process-wide variables built into the system and control the way it looks and acts, since they are process-wide, they are inherited by any child shells or processes.
  • Shell variables: Are typically listed in lowercase and are only valid in the shell they are set in.

Viewing and Modifying Environment Variables

Use the env command to view all you default environment variables:

Environment variables are always uppercase, as we can see SHELL, WINDOWID and COLORTERM

To view all environment variables, including shell variables, local variables, and shell functions such as any user-defined variables and command aliases, we can use the set command. I'll use it with more so it's a bit more manageable to view:

set | more

Changing Variable Values

We can change a variable by providing the name, followed by an equals sign and the new value

HISTSIZE=200

We've changed the value of HISTSIZE but only in our particular environment, if we wanted to make this change permanent we would use the export command. export will set the new value from your current environment to any new forked child processes, allowing new processes to inherit the exported variables.

export HISTSIZE

NOTE: Before making any changes, you might want to save a copy of the current value echo $VARIABLE> ~/valueOfVARIABLE.txt or you might even want to keep a copy of all current variables values set> ~/valueofALLon02252020.txt

Another variable you might want to modify is the PS1 variable. It has a set of placeholders for information you want to display in your shell prompt:

  • \u The name of the current user
  • \h The hostname
  • \w The base name of the current working directory

The PATH variable

The PATH variable controls where on your system your shell will look for commands. If the bash shell doesn't find the command in one of the directories in your PATH variables, it will return the error command not found

Let's see which directories are stored in your PATH variable

echo $PATH

There are the directories where my terminal will search for any command. Each directory is separated by a colon (:)

Let's say I have some commands in the /home/azureuser/gpstools directory that I would add to my PATH We can add a directory to the PATH variable by entering

PATH=$PATH:/directory/to/add

This will assign the original PATH plus the /directory/to/add/

DO NOT DO PATH=/directory/to/add that will replace everything and add the new directory, you want to append, not replace.

Creating a User-Defined Variable

We can create our own variables by following this syntax

MYVARIABLE="VALUE"

If you need it to persist, don't forget to export it. export MYVARIABLE and if you want to delete any variable, use the unset command, just double check before deleting anything. unset MYVARIABLE