Korn Shell Arrays
Here are a few useful examples of how to use data arrays within Korn shell. Arrays are a great tool for storing user input and other data for quick, on-the-fly access. If, for example, you script repeatedly reads the same input file, you can speed things up by converting the file into an array (depending, of course, on the size of the file).
Create a simple array
set -A termnames gl35a t2000 s531 vt99 # array elements are separated by blanks, TABs, or NEWLINEs
set -A arrayname $(< filename) # where "filename" is the file that contains array values
typeset -A StateTax
StateTax[New Jersey]=0.06
print ${StateTax[New Jersey]}
Read the array
print ${#termnames[*]} #shows the number of elements in the array; “*” can be replaced by “@”
print ${termnames[*]} #shows all values
print ${termnames[0]} #shows the first value
for i in 0 3 4 #show values 0, 3, and 4
do
print ${termnames[$i]}
doneprint ${termnames[3]} is equivalent to print ${termnames[2+1]}
Sample script 1
set -A termnames gl35a t2000 s531 vt99
select term in `print ${termnames[*]}`
do
if [[ -n $term ]]
then
TERM=${termnames[REPLY-1]}
print “TERM is $TERM”
break
fi
done
Read a file into an array, one line at a time
i=0
cat /var/log/messages | while read LINE
do
msgarray[$i]=”${LINE}”
(( i = i + 1 ))
done
Print values from the array
i=0 #array element count begins with “0″
while [ $i -lt ${#termnames[*]} ]
do
print ${termnames[$i]}
(( i = i + 1 ))
done
Put the output of a command into an array
set -A dt `date`
> print ${#dt[*]}
6
> print ${dt[*]}
Wed Jan 30 00:55:04 EST 2008
Sample script 2
#!/bin/ksh
#
# parms2array: store the passed parameters in an array
# source: http://open.itworld.com/5040/nls_unix_korn060810/page_1.html
set -A parms $*
print “You supplied ${#parms[@]} parameters:”
i=0
while [ $i -le ${#parms[@]} ]
do
print ${parms[$i]}
(( i=i+1 ))
done
> ./parms2array red orange yellow green blue indigo violet
You supplied 7 parameters:
red
orange
yellow
green
blue
indigo
violet
Popularity: 4% [?]
Related posts:


