open.itworld.com
  Search  
Security Home Page Security Webcasts Security White Papers Security Newsletters Security News Open Topics Careers ITworld Voices ITwhirled The Security site of ITworld.com

Unix Tip: Using indexed arrays in the Korn shell

ITworld.com 8/10/2006

Sandra Henry-Stocker, ITworld.com

Send in your Unix questions today!

See additional Unix tips and tricks

One of the most convenient ways to manipulate information in scripts is to store it in an array. Arrays facilitate looping through lists of related values, keeping track of an ever changing number of items and relating descriptive text with the items that they describe. As a very simple example, consider the colors of a rainbow. You can always loop through a list of rainbow colors like this:

for color in red orange yellow green blue indigo violet
do
   echo I like $color
done
That's convenient enough, but it can get tiresome if you want to loop through the same list at numerous places in a script and troublesome if your list of values is defined on the fly.

To store these same values in an array, you can add each array element to a specific position in the array like this:
rainbow[0]="red"
rainbow[1]="orange"
rainbow[2]="yellow"
rainbow[3]="green"
rainbow[4]="blue"
rainbow[5]="indigo"
rainbow[6]="violet"
If you prefer a more concise command for populating your Korn shell array, try this:
set -A color red orange yellow green blue indigo violet
Using either approach to loading your array, you can loop through it very easily:
i=1

while [ $i -le ${#rainbow[@]} ]
do
    print ${rainbow[$i]}
    (( i=i+1 ))
done
The "${#rainbow[@]}" item in the while statement reflects the size of the array (i.e., the number of data elements in the array).

The types of array we have been working with above are referred to as "indexed arrays". These arrays employ numeric values -- 1, 2, 3 and so on -- as their indices. Since most scripting and programming languages start indexed arrays with element 0, we have done so in the examples above. If you prefer, you can start an array with 1 and have it work the same (see example below), but the "set -A" syntax and general convention suggest you stick with 0.
#!/bin/ksh

rainbow[1]="red"
rainbow[2]="orange"
rainbow[3]="yellow"
rainbow[4]="green"
rainbow[5]="blue"
rainbow[6]="indigo"
rainbow[7]="violet"

i=1

print "There are ${#rainbow[@]} colors in the rainbow:"

while [ $i -le ${#rainbow[@]} ]
do
    print ${rainbow[$i]}
    (( i=i+1 ))
done
Arrays are especially useful when you don't know how many values your script is going to be handling when you write it. Since an array can accommodate a variable number of elements, we can set one up in a number of ways. Reading from command output, we can assign each portion of the date command output to an array like this:
$ set -A dt `date`
To display just the day of the week, we could then do this:
$ echo ${dt[0]}
Thu
Of course there are easier ways to get the day of the week from the date command, but any time you want to separate process each piece of text in the output of a command, an indexed array is an option.

If we want to assign to an array all of the parameters that are supplied to a script, we can do that like this:
#!/bin/ksh
#
# parms2array: store the passed parameters in an array

set -A parms $*

print "You supplied ${#parms[@]} parameters:"

i=0

while [ $i -le ${#parms[@]} ]
do
    print ${parms[$i]}
    (( i=i+1 ))
done
Of course, the parameters will already be associated with $1, $2, $3 and so on. However, depending on other commands that you use in your script, you might end up reusing these parameters for other things. Saving the original parameters in a "parms" array can be very useful.

Here are the colors of the rainbow processed by the parms2array script:
$ ./parms2array red orange yellow green blue indigo violet
You supplied 7 parameters:
red
orange
yellow
green
blue
indigo
violet

On this topic

 

Sandra Henry-Stocker has been administering Unix systems for more than 18 years. She describes herself as "USL" (Unix as a second language) but remembers enough English to write books and buy groceries. She currently works for TeleCommunication Systems, a wireless communications company, in Annapolis, Maryland, where no one else necessarily shares any of her opinions. She lives with her second family on a small farm on Maryland's Eastern Shore. Send comments and suggestions to bugfarm@gmail.com.




Sponsored Links

Sign up for a Microsoft Dynamics® CRM WEBCAST
Hear globally recognized leaders in customer strategy discuss the importance and evolution of CRM.
TRY NEW SUN SERVERS FREE for 60 Days!
Test The Latest Sun Servers In Your Environment BEFORE YOU BUY. Pay Nothing, Not Even Shipping.
Workflow Enabled Help Desk & IT Service Management
Automate service desk activities and integrate processes across IT. Learn more here.
Sign up for a FREE NETWORK RISK ASSESSMENT!
MORE THAN 70% OF NETWORKS ARE INFECTED by hidden Malware. Find out if your network is infected now!
Enterprise IP Goes Mobile
To maximize full productivity, companies must integrate their mobile applications with the IP network.
» Buy a link now

Advertisements
Sponsored links
Top 5 Reasons to Combine App Performance and Security
Locate Hidden Software on business PCs with this free tool
KODAK i1400 Series Scanners stand up to the challenge
Bring harmony to your mix of UNIX-Linux-Windows computing environments
 Home   Open source  Operating systems  Unix
www.itworld.com    open.itworld.com     security.itworld.com     smallbusiness.itworld.com
storage.itworld.com     utilitycomputing.itworld.com     wireless.itworld.com

 
Contact Us   About Us   Privacy Policy    Terms of Service   Reprints  

CIO   Computerworld   CSO   GamePro   Games.net   IDG Connect   IDG World Expo   Infoworld   ITworld   JavaWorld   LinuxWorld  MacUser   Macworld   Network World   PC World   Playlist  

Copyright © Computerworld, Inc. All rights reserved

Reproduction in whole or in part in any form or medium without express written permission of Computerworld Inc. is prohibited. Computerworld and Computerworld.com and the respective logos are trademarks of International Data Group Inc.