Skip to main content
p. 22

2.8 Environment and Shell Variables

The shell can store temporary variables, called shell variables, containing the values of text strings. Shell variables are very useful for keeping track of values in scripts, and some shell variables control the way the shell behaves. (For example, the bash shell reads the PS1 variable before displaying the prompt.)

p. 23

To assign a value to a shell variable, use the equal sign (=). Here’s a simple example:

$ 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). You’ll learn about the many uses of shell variables in Chapter 11.

note

Don’t put any spaces around the = when assigning a variable.

An environment variable is like a shell variable, but it’s not specific to the shell. All processes on Unix systems have environment variable storage. The main difference between environment and shell variables is that the operating system passes all of your shell’s environment variables to programs that the shell runs, whereas shell variables cannot be accessed in the commands that you run.

You assign an environment variable with the shell’s export command. For example, if you’d like to make the $STUFF shell variable into an environment variable, use the following:

$ STUFF=blah
$ export STUFF

Because child processes inherit environment variables from their parent, many programs read them for configuration and options. For example, you can put your favorite less command-line options in the LESS environment variable, and less will use those options when you run it. (Many manual pages contain a section labeled ENVIRONMENT that describes these variables.)