November
10, 2003 -
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. Next week's tip will show you
how to automatically determine the number of
elements in an array for
accessing/processing array elements from
within a shell script.
Although there are some who contend that the
Korn shell array is not very useful, I
disagree. Under the right
circumstances and with a little technical
creativity, it can be extremely powerful.
|
|
|
|
|
|
|
|
|
|
|
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
|
|