KSH For Loop Array: Iterate Through Array Values

by on July 7, 2009 · 4 comments· LAST UPDATED July 7, 2010

in

How do I use ksh for loop to iterate thought array values under UNIX / Linux / BSD operating systems?

You can define array as follows:

set -A arrayName value1 value2 value3

For example, create an array called characters with three values as follows:

set -A characters Mugen Jin Fuu

To print first value, enter:

echo ${characters[0]}

To print 3rd and last value, enter:

echo ${characters[2]}

To print all values, enter:

echo ${characters[@]}

To count number of items in an array called characters, enter:

echo ${#characters[@]}

You can use for loop as follows to iterate through all values:

for i in ${characters[@]}; do echo "Samurai Champloo character - $i"; done

Sample outputs:

Samurai Champloo character - Mugen
Samurai Champloo character - Jin
Samurai Champloo character - Fuu

You can add two more items as follows to exiting array:

characters[3]="Sunflower-Samurai"
characters[4]="Detective-Manzo"

Sample Shell Script

#!/bin/ksh
# set array called nameservers
set -A nameservers 192.168.1.1 192.168.1.5 202.54.1.5
 
# print all name servers
for i in ${nameservers[@]
do
	echo $i
done
 
TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 4 comments… read them below or add one }

1 Nisrine August 19, 2011 at 7:05 am

If i need to print the next value in the array if a certain condition is verified
for example:
for i in “${array[@]}”
do
if(….) then
echo $(i+1)
fi
done

$(i+1) is wrong what can i do?

Reply

2 Jason October 16, 2012 at 12:26 pm

Hi Nisrine,

I hope my necromancing is welcome here, in case your issue is still relevant.

$(ì+1) should actually be $((i+1)), since double parentheses evaluate mathematical expressions.

I hope this helps someone!

Jason

Reply

3 Nisrine October 16, 2012 at 2:14 pm

Thank you for ur reply! working!

Reply

4 Ken June 18, 2012 at 9:21 pm

Excellent just what i needed for looping through an array

Reply

Leave a Comment

Tagged as: , , , , , , , , , , , , ,

Previous Faq:

Next Faq: