|
|
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:
$The C shell equivalent of this is as follows:MYVARIABLE=hello
$echo MYVARIABLE
MYVARIABLE $echo $MYVARIABLE
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:set MY=hello
%echo MY
MY %echo $MY
hello %
$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).MYVARIABLE=hello
$echo $MYVARIABLE
hello $echo ${MYVARIABLE}_there
hello_there $echo $MYVARIABLE_there
$
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.