November
17, 2003 -
Korn
Shell Arrays - Array Operators - Part II
|
|
After
reading last week's 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.
Next week we'll get a little more creative.
|
|
|
|
|
|
|
|
|
|
|
Learn
more...
If you are new to the UNIX or Linux
operating system and would like to learn
more, you may want to consider
registering for LiveFire Labs' UNIX
and Linux Operating System Fundamentals
online training course.
If you already have a solid grasp of the
fundamentals but would like to learn more
about the Korn shell and basic and
advanced shell scripting, taking our Korn
Shell Scripting course will be
beneficial to you.
Our
innovative hands-on training model allows
you to learn
UNIX by completing hands-on
exercises on real servers in our Internet
Lab.
More
Tips...
· Popular
UNIX Tips from the Past
|
|