1.8 Environment and Shell Variables

1.8 Environment and Shell Variables

The shell can store temporary variables, called shell variables, that store the values of text strings. Shell variables are very useful for keeping track of state in scripts, and some shell variables control the way the shell behaves (for example, the PS1 variable controls the prompt). To assign a value to a shell variable, use the equal sign (=):

STUFF=blah

The preceding example sets the value of the variable named STUFF to blah. To access this variable, use $STUFF (for example, try running echo $STUFF).

An environment variable is like a shell variable, but is not specific to the shell. All programs on Unix systems have environment variable storage. The difference that you will notice is that the operating system passes all of your shell's environment variables to programs that the shell runs, whereas shell variables are not accessible by the commands that you run. Some programs use environment variables for configuration and options. For example, you can put your favorite less command-line options in the LESS environment variable, and less will use these when you run it. Many manual pages contain a section marked ENVIRONMENT that describes these variables.

You can assign a new environment variable just as you would a shell variable, except that after creating the variable, you must run the export operation to transfer the variable to the shell's environment variable storage. The following sequence of commands assigns a value to STUFF and changes it into an environment variable:

STUFF=blah
export STUFF