next up previous contents
Next: Variable Substitutions Up: The Bourne Shell Previous: Special Characters

 

Variables

This is where the shell gets interesting. Variables add a level of generality to the environment. A variable is simply a name that acts as a placeholder for a value or set of values (an array which will be covered in later sections). In the Bourne shell there are four different types of variables:



User defined variables are fairly straightforward. In the Bourne shell they take the following form:

$ size=1024
$ MY_ADDRESS=buchanan@phys.ualberta.ca
$ greeting='Welcome to the Bourne shell'

To access a variable, a $ must be placed in front of the variable name or else the shell will not realize that what follows is not a command. The shell will then attempt to execute the command and return an error message. An example of accessing a user defined variable is then

$ echo You can e-mail me at $MY_ADDRESS

You can e-mail me at buchanan@phys.ualberta.ca

The above can be used to demonstrate the difference between single- and double-quote handling of strings. If single quotes are used to enclose the string, the shell will not make the variable substitution as it treats the $ as a text character rather than a signal that a variable is coming:

$ echo 'You can e-mail me at $MY_ADDRESS'

You can e-mail me at $MY_ADDRESS

Double quotes however, will allow the shell to recognize the variable and pass its value to the echo command:

$ echo "You can e-mail me at $MY_ADDRESS"

You can e-mail me at buchanan@phys.ualberta.ca

Variable names can be nested as well. This is another way to say that one variable can be set equal to another variable which contains another, etcetera.

$ today=Tuesday
$ day=$today
$ echo The day of the week is $day

The day of the week is Tuesday

When assigning a value to a variable, it is important to leave no white space. This is because the assignment is terminated by white space, unless the appropriate quotation characters enclose the string value. This allows more than one variable assignment to be made on a single line:

$ a=cat b=dog c=elephant

It is important however to realize that the assignments are processed from right to left and therefore if the following assignments were made:

$ VAR1=$VAR2 VAR2=hello

the value of VAR1 would be hello whereas if the the order was reversed:

$ VAR1=hello VAR2=$VAR1

the value of VAR2 would be undefined. This is because VAR2 is assigned the value of VAR1 before VAR1 has been given a value.

Variable assignments can also be removed using the unset command. For example,

$ VAR="Hello"
$ echo $VAR  
Hello
$ unset VAR
$ echo $VAR

$




next up previous contents
Next: Variable Substitutions Up: The Bourne Shell Previous: Special Characters

Douglas M Gingrich
Mon Apr 27 15:25:49 MDT 1998