"Taking a LiveFire Labs' course is an excellent way to learn
Linux/Unix. The lessons are well thought out, the material is
explained thoroughly, and you get to perform exercises on a real
Linux/Unix box. It was money well spent."
Ray S.
Pembrook Pines, Florida
LiveFire Labs' UNIX and Linux Operating System Fundamentals
course was very enjoyable. Although I regularly used UNIX systems
for 16 years, I haven't done so since 2000. This course was a
great refresher. The exercises were fun and helped me gain a real
feel for working with UNIX/Linux OS. Thanks very much!"
Ming Sabourin
Senior Technical Writer
Nuance Communications, Inc.
Montréal, Canada
Read more student testimonials...
Receive UNIX Tips, Tricks, and Shell Scripts by Email
LiveFire Labs' UNIX Tip,
Trick, or Shell Script of the Week
Korn Shell Arrays - Assigning and Accessing Values - Part I
Another type of variable supported by the Korn
shell is the array. Briefly, an array contains a collection of values
(elements) that may be accessed individually or as a group. Although
newer versions of the Korn shell support more than one type of array,
this tip will only apply to indexed arrays.
When assigning or accessing array elements, a subscript is used to
indicate each element's position within the array. The subscript is
enclosed by brackets after the array name:
arrayname[subscript]
The first element in an array uses a subscript of 0, and the last
element position (subscript value) is dependent on what version of the
Korn shell you are using. Review your system's Korn shell (ksh) man
page to identify this value.
In this first example, the colors red, green, and blue are assigned to
the first three positions of an array named colors:
$ 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
$
Notice that a variable (i) was used for the subscript value each time
through the loop.