DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Configuring and working with the shells

Setting shell variables

To set a variable in the shell, use an equal sign to assign it a value. If the variable does not already exist, it is created. For example:

MYVARIABLE=hello

It is common practice to use all uppercase letters for the name of variables, to distinguish them from UNIX system commands (that are almost always lowercase).

To refer to the value of a variable, prefix the variable's name with a ``$'' symbol. If you omit the ``$'', the shell will assume you are referring to the name of the variable, not its current value. For example, in the Bourne and Korn shells:

   $ MYVARIABLE=hello
   $ echo MYVARIABLE
   MYVARIABLE
   $ echo $MYVARIABLE
   hello
   $
The C shell equivalent of this is as follows:
   % set MY=hello
   % echo MY
   MY
   % echo $MY
   hello
   %
You may sometimes see variable names enclosed in braces ({}) within a reference. The braces are used to delimit the name of the variable. For example echo ${MYVARIABLE} could be used instead of echo $MYVARIABLE. This is particularly useful when you want to concatenate the contents of a variable with another word. For example:
   $ MYVARIABLE=hello
   $ echo $MYVARIABLE
   hello
   $ echo ${MYVARIABLE}_there
   hello_there
   $ echo $MYVARIABLE_there
   

$

In the third echo command, because MYVARIABLE is not separated from ``_there'' the shell tries to substitute a variable called MYVARIABLE_there (which does not exist).

It is a good idea to make a habit of placing variable names in parentheses whenever there is any doubt, to reduce the likelihood of this kind of error.


Next topic: Setting environment variables
Previous topic: Understanding variables

© 2003 Caldera International, Inc. All rights reserved.
SCO OpenServer Release 5.0.7 -- 11 February 2003