"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 - Array Operators - Part II
After reading last week's ksh array tip, you should have a
basic understanding of how to assign values (elements) to an indexed
array, and then access them individually based on their position in
the array.
One example from last week demonstrated how to access and print each
array element using a while loop:
$ i=0
$ while [ $i -lt 3 ]
> do
> print ${colors[$i]}
> (( i=i+1 ))
> done
RED
GREEN
BLUE
$
Hard-coding the number of elements in the array is fine for
demonstrating a new concept, but obviously not very practical when it
comes to using it within a shell script. Most of the time you will
not know how may elements will be stored in the array, or the number
may be dynamic - changing each time the script is invoked.
Fortunately, there is an operator for determining the number of array
elements:
${#arrayname[*]}
Comparing this to the syntax used for accessing individual array
elements,
${arrayname[subscript]}
you should notice the addition of the # in front of the array name,
and the use of an asterisk (*) in place of a subscript. Armed with
this new operator, let's tweak our while loop to print the previously
defined elements:
$ i=0
$ NUM_OF_ELEMENTS=${#colors[*]}
$ while [ $i -lt $NUM_OF_ELEMENTS ]
> do
> print ${colors[$i]}
> (( i=i+1 ))
> done
RED
GREEN
BLUE
$
If we wanted to compress the code a little, the operator to detect the
number of array elements could be embedded within the while statement:
$ i=0
$ while [ $i -lt ${#colors[*]} ]
> do
> print ${colors[$i]}
> (( i=i+1 ))
> done
RED
GREEN
BLUE
$
On a related note, there may be times when you need to print the
entire element list at once. This can be accomplished using the
following operator:
$ print ${colors[*]}
RED GREEN BLUE
$
Notice that an asterisk is used instead of a subscript.