Shell Variables

In addition to the environment, shells maintain a similar set of variables for their own use. These variables are not passed down to child processes, and are only used by the shell.

Like environment variables, you can create shell variables with any name and value you like. However, there are many shell variable names that are reserved for specific purposes. For example, each shell uses a special shell variable to define the shell prompt.

In Bourne-shell derivatives, this variable is called PS1. To set a shell variable in Bourne-shell derivatives, we use a simple assignment. The export command in the previous section actually sets a shell variable called TERM and then exports (copies) it to the environment.

shell-prompt: PS1="peregrine: "


Again, there cannot be any white space before or after the '='. This is how Bourne shell and its derivatives distinguish a variable assignment from a command. If we wrote PS1 = "unixdev1: ", the shell would think that PS1 is a command, '=' is the first argument, and "unixdev1: " is the second argument. PS1 is a variable, not a command.

In C shell derivatives, the variable is called prompt, and is set using the set command:

shell-prompt: set prompt="unixdev1: "


The syntax for set is slightly different than for setenv. Set uses an '=' while setenv uses a space. Unlike a Bourne shell variable assignment, the set command can tolerate white space around the '='.

Shell prompt variables may contain certain special symbols to represent dynamic information that you might want to include in your shell prompt, such as the host name, command counter, current working directory, etc. Consult the documentation on your shell for details.

In all shells, you can view the current shell variables by typing set with no arguments:

shell-prompt: set

Besides special variables like PS1 and prompt, shell variables are primarily used in shell scripts, much like variables in a C or Java program. Shell scripts are covered in Chapter 4, Unix Shell Scripting.



Be sure to thoroughly review the instructions in Section 2, “Practice Problem Instructions” before doing the practice problems below.
  1. What is the difference between shell variables and environment variables?

  2. Show how to set the shell prompt to "Unixdev1: " in:

    1. Bourne shell

    2. C shell

  3. How can you view a list of all current shell variables and their values?