7/30/2007

Korn Shell Arrays

$ colors[0]=RED
$ colors[1]=GREEN
$ colors[2]=BLUE

Alternatively, you can perform the same assignments using a single command:

$ set -A colors RED GREEN BLUE

Adding a dollar sign and an opening brace to the front of the general syntax and a closing brace on the end allows you to access individual array elements:

${arrayname[subscript]}

Using the array we defined above, let's access (print) each array element one by one:

$ print ${colors[0]}
RED
$ print ${colors[1]}
GREEN
$ print ${colors[2]}
BLUE
$

If you access an array without specifying a subscript, 0 will be used:

$ print ${colors[]}
RED
$

The while construct can be used to loop through each position in the array:

$ i=0
$ while [ $i -lt 3 ]
> do
> print ${colors[$i]}
> (( i=i+1 ))
> done
RED
GREEN
BLUE