home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 45.33 Testing Two Strings with One case Statement Chapter 45
Shell Programming for the Initiated
Next: 45.35 Using a Control Character in a Script
 

45.34 Arrays in the Bourne Shell

The C shell ( 47.5 ) , awk ( 33.11 ) , 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 ( 44.19 ) 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 ( 8.10 ) command does the trick. As an example, if the n shell variable stores the array index ( 1 , 2 , 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 ( 44.16 ) 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


Previous: 45.33 Testing Two Strings with One case Statement UNIX Power Tools Next: 45.35 Using a Control Character in a Script
45.33 Testing Two Strings with One case Statement Book Index 45.35 Using a Control Character in a Script

The UNIX CD Bookshelf Navigation The UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System