Translate

Archives

Korn Shell Multidimensional Arrays

The bash shell only supports single dimension arrays. Korn Shell 93 (ksh93), on the other hand, supports multidimensional arrays although this feature is poorly documented.

Here is a simple example which demonstrates how to create and use a multidimensional array:

#!/bin/ksh93

for i in 1 2 3
do
   for j in 4 5 6
   do
       for k in 7 8 9
       do
           array[$i][$j][$k]=$(( i + j + k ))
#          echo ${array[$i][$j][$k]}
       done
   done
done

for i in 1 2 3
do
   echo ${array[$i][4][7]}
done


It outputs:

12
13
14


Note – multidimensional associative arrays are not supported.

1 comment to Korn Shell Multidimensional Arrays

  • Boris

    Thx for your post, it was really helpfull for a project I’m working on.
    In a ksh93 script, I’m trying to use a two dimensions array. I need to initialize each cell with a string “B1”. Here is part of my code :
    #!/bin/ksh93
    num_cols=192
    echo Number of cols : $num_cols
    #init matrix to blank
    echo initialize the matrix
    i=1
    while [ $i -le $num_rows ]; do
    j=1
    while [ $j -le $num_cols ]; do
    matrix[$i][$j]=”B1″
    echo $matrix[$i][$j]
    j=$(($j+1))
    done
    i=$(($i+1))
    done

    when I execute this, I get that error and I can’t figure out why :
    + num_cols=192
    + echo echo Number of cols : 192 echo Number of cols : 192
    + echo initialize the matrix initialize the matrix
    + i=1
    + [ 1 -le 15 ]
    + j=1
    + [ 1 -le 192 ]
    + matrix2html.sh[38]: matrix: subscript out of range

    I also tryed your basic code proposed here up as a test and it’s working fine.
    I’m a little bit lost.
    Thx.