CIS 201: Linux Shell Scripting

lewing@isc.tamu.edu

Gabelli School of Business, CIS Department

| CISWEB Doug White | RWU Main | White Hat Research | Email Doug | Access Data |

CIS 201: Using Arrays

If your lab 3 is a mess due to 10 variable names, consider using an array to solve the problem

Arrays have challenging syntax but it makes an easy solution.

Say you want to load 5 things into variables (100, 75, 100, 90, 85)

Arrays are variables that have multiple values. A spreadsheet is a good example of a two dimensional array. ksh has only one dimensional arrays so they are things like race times per person.

Unlike C++, arrays in ksh are simple and just declared on the fly with [] to indicate which item in the array you are seeing.

For instance, suppose you want to put 5 times into a stack of items:

foo[0]=56

foo[1]=66

foo[2]=71

foo[3]=19

foo[4]=21

All of these things are in a variable named foo which has multiple subfields.

The syntax for retreiving the vals is weird

echo ${foo[4]} will print out 21

So what's the point? Suppose we want to average these things:

Now we can use a loop

for (( k=0;k<5;k++ ))

do

sum+=${foo[k]}

done

echo $(sum/k)

 

| Contact | © 2005 Secure Technology, LLC. |