KSH For Loop Array: Iterate Through Array Values

last updated in Categories , ,

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

The ksh shell supports two types of arrays:


  1. Indexed array
  2. associative array

[donotprint][/donotprint]An element of a ksh array variable is referenced by a subscript. The value of all non-negative subscripts must be in the range of 0 through 4,194,303.


You can define array as follows either as an associative array or to be an indexed array.

Syntax for an indexed array


OR use set command as follows:

set -A arrayName value1 value2 value3

Syntax for an associative array

typeset -A employees


set -A arrayName val1 val2 val3

Examples for ksh indexed array

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:


Sample Shell Script

# set array called nameservers
set -A nameservers
# print all name servers
for i in ${nameservers[@]}
	echo $i

Sample outputs:

Fig.01: Ksh for loop array ns demo
Fig.01: Ksh for loop array ns demo

Ksh associative arrays examples

## set associative array ##
typeset -A ns 
## Add values ##
ns[home]="" ## home dns server ip 
ns[isp]=""    ## my isp dns server ip
ns[google]=""     ## google public dns server ip
## Okay, display values #
print "${ns[home]}"
print "${ns[isp]}"
print "${ns[google]}"
## Count  number of items in an array #
print "${!ns[@]}"
## Use for loop to print all items in an array##
for i in "${!ns[@]}"
   echo "ns[$i] value is ${ns[$i]}"

Sample outputs:

ns[google] value is
ns[home] value is
ns[isp] value is

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.


7 comment

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

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

    1. 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!


Leave a Comment