2.21. Arrays

Bourne shell does not support arrays, but some commands can process strings containing multiple words separated by white space.

#!/bin/sh

names="Barney Bert Billy Bob Brad Brett Brody"
for name in $names; do
    ...
done
	

C shell supports basic arrays. One advantage of this is that we can create lists of strings where some of the elements contain white space.

An array constant is indicated by a list enclosed in parenthesis.

Each array element is identified by an integer subscript.

We can also use a range of subscripts, separated by '-'.

#!/bin/csh -ef

set names=("Bob Newhart" "Bob Marley" "Bobcat Goldthwait")
set c=1
while ( $c <= $#names )
    printf "$names[$c]\n"
    @ c++
end

printf "$names[2-3]\n"

Caution

The foreach command is not designed to work with arrays. It is designed to break a string into white space-separated tokens. Hence, given an array, foreach will view is as one large string and then break it wherever there is white space, which could break individual array elements into multiple pieces.

The $argv variable containing command-line arguments is an array. Hence, the $#argv variable is not special to $argv, but just another example of referencing the number of elements in an array.