Shell variables are really just the "general case" of . If you're a programmer, remember that a UNIX shell really runs an interpreted programming language. Shell variables belong to the shell; you can set them, print them, and work with them much as you can in a C program (or a FORTRAN program or a BASIC program). If you're not a programmer, just remember that shell variables are pigeonholes that store information for you or your shell to use.
If you've read the section on environment variables, you realize that we defined them in exactly the same way. How are shell variables different from environment variables? Whenever you start a new shell or a UNIX program, it inherits all of its parent's environment variables. However, it does not inherit any shell variables; it starts with a clean slate. If you're a programmer, you can think of environment variables as "global" variables, while shell variables are "local" variables. By convention, shell variables have lowercase names.
Just as some programs use certain environment variables, the shell expects to use certain shell variables. For example, the C shell uses the variable to determine how many of your previous commands to remember; if the variable is defined, the C shell prevents you from damaging files by making mistakes with standard output. Most users insert code into their to define these important variables appropriately.
To set a shell variable, use one of these commands:
This is important: giving a variable a null value is not the same as deleting the value. Some programs look at variables to see whether or not they exist; they don't care what the actual value is, and an empty value is as good as anything else. If you want to make the shell forget that a variable ever existed, use the unset command. Unfortunately, older Bourne shells don't have a command like unset :
If you want to list all of your environment variables, use the
(Berkeley UNIX) or
If you want to list all of your Bourne or C shell variables, just type
(While the example above gives a C shell prompt, this command works in all UNIX shells.)
Whenever you need the value of a shell variable - not just with
you need to put a dollar sign (
But that's getting us out of the range of interactive variable use and into.