Arrays in the Bourne Shell
The C shell (), awk (), the Korn shell, and some other UNIX command interpreters have built-in array support. The standard Bourne shell doesn't, though its command line is a sort-of array that you can store with the set () command - and get stored values through $1
, $2
, etc.
You can store and use Bourne shell variables - with names like array1, array2, and so on - to simulate an array with elements 1, 2, and so on. The eval () command does the trick. As an example, if the n shell variable stores the array index (, , etc.), you can store an element of the array named part with:
eval part$n="value
"
and use its value with:
eval echo "The part is \$part$n."
You need the extra quoting in that last command because eval scans the command line twice. The really important part is $part$n
-on the first pass, the shell interprets $n
, strips off the backslash, and leaves a line like:
echo "The part is $part5."
The next pass gives the value of the part5 variable.
To store a line of text with multiple words into these fake array elements, the set command won't work. A for loop () usually will. For example, to read a line of text into the temp variable and store it in an "array" named part:
expr |
echo "Enter the line: \c" read temp n=0 for word in $temp do n=`expr $n + 1` eval part$n="$word" done |
---|
The first word from $temp
goes into the variable part1, the second into part2, and so on.
- JP