Operating System - HP-UX
1843964 Members
2020 Online
110226 Solutions
New Discussion

Using arrays in ksh script

 
SOLVED
Go to solution

Using arrays in ksh script

Hi,
I'm trying to use arrays in a ksh script.
I'm implementing an example found on the forum.
But it doesn't work and I can't see why !
the commands are :
DAYS[0]=Mon
DAYS[1]=Tue
DAYS[2]=Wed
print $DAYS
print $DAYS[0]
print $DAYS[1]
print $DAYS[2]

and the result is :
DAYS: not found
DAYS: not found
DAYS: not found



Where is the problem ? (Am I using a wrong ksh ?)
Thanks for your help.

6 REPLIES 6
Mark Grant
Honored Contributor
Solution

Re: Using arrays in ksh script

This is how arrays are supposed to be used.

colour[0]=red
colour[1]=blue
colour[2]=red
colour[3]=green
colour[4]=green
colour[5]=blue
colour[6]=yellow
colour[7]=cyan
colour[8]=red
colour[9]=blue

echo ${colour[2]}

That will output "red"
Never preceed any demonstration with anything more predictive than "watch this"
Mark Grant
Honored Contributor

Re: Using arrays in ksh script

Although your example hasn't come out in the example you posted, I think it looks like you have missed outh the "${" and "}" around the whole variable thing.
Never preceed any demonstration with anything more predictive than "watch this"
A. Clay Stephenson
Acclaimed Contributor

Re: Using arrays in ksh script

This is one of those times when discipline counts. ALWAYS enclose shell variables in braces and you will have no problems.

#!/usr/bin/ksh

DAYS[0]="Mon"
DAYS[1]="Tue"
DAYS[2]="Wed"

#Now try this:
print $DAYS[1]
print ${DAYS[1]}

If it ain't broke, I can fix that.
Chris Vail
Honored Contributor

Re: Using arrays in ksh script

Here's a re-write of Mark's script:
colour[0]=red
colour[1]=blue
colour[2]=red
colour[3]=green
colour[4]=green
colour[5]=blue
colour[6]=yellow
colour[7]=cyan
colour[8]=red
colour[9]=blue
COUNTER=0
while test "$COUNTER" -lt "10"
do
echo $COUNTER ${colour[$COUNTER]}
(( COUNTER = "$COUNTER" + "1" ))
done

You can see the syntax of how the subscript works then.

Re: Using arrays in ksh script

Thanks.
It's MUCH EASIER this way !
Sridhar Bhaskarla
Honored Contributor

Re: Using arrays in ksh script

Hi,

It's easy to get confused with Arrays. Following script may give you little more information on ARRAYs.

set -A ARRAY

ARRAY[0]="elem 1 "
ARRAY[1]="elem 2"
ARRAY[2]="elem 3"
ARRAY[3]="elem 4"
ARRAY[4]="elem 5"

typeset -i num_elms=${#ARRAY[@]}
typeset -i count=0

while [ $count -lt num_elms ]
do
echo "ARRAY[$count] is ${ARRAY[$count]}"
(( count = $count + 1 ))
done

-Sri
You may be disappointed if you fail, but you are doomed if you don't try