next up previous contents
Next: Global or Environment Variables Up: Variables Previous: User Defined Variables

Array Variables

The Bourne shell restricted variables to single values. The C shell imposes no such limit. It provides the user with the use of array variables, which are variables that contain two or more discreet values. Ignoring proper C shell notation for a moment, an example of an array would be a variable called alphabet which contained each of the 26 letters A through Z. To access a particular letter the variable might be followed by the number of the sequence which contained the desired letter. For example, the letter C might be referred to as alphabet(3), while Z would be referred to as alphabet(26). An array is a nice way to store related elements which could be accessed under the same name. In the C shell, array variables can be set as follows. All of the array elements can be set at one time by enclosing the list with parentheses and separating the elements with white space (usually spaces). For example, to set an array of pets:

% set PETS=(Cat Dog Goldfish Horse Boa Hamster)

To access an element of a variable the variable name is followed by square brackets containing the element number:

% echo $PETS[3]
% echo $PETS[3-5]
Goldfish Horse Boa

The example illustrates how more than a single element can be accessed at once using the - operator. If this operator is placed before or after a number it will access all of the elements up to and including or including to the end of the list respectively. For example,

% echo $PETS[-3]
Cat Dog Goldfish

The entire array variable list can be accessed by placing an * in the square brackets. Table 4.2 summerizes the ways to access array elements:

Table 4.2:  Ways to access array elements.

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