How to define a multi-dimensional array in a unix shell script [duplicate]

Tag: arrays , bash , unix , sh , ksh Author: shaneccjj Date: 2013-09-18

This question already has an answer here:

How can I implement a multi-dimensional array in a unix shell script? The solution should not only work for bash but as well for other unix shells.

There is a similar question specific for bash. I posted the same answer there, but I wanted to re-ask the question in a more generic way so that not only users looking for a bash solution get the answer.

Other Answer1

Independent of the shell being used (sh, ksh, bash, ...) the following approach works pretty well for n-dimensional arrays (the sample covers a 2-dimensional array).

In the sample the line-separator (1st dimension) is the space character. For introducing a field separator (2nd dimension) the standard unix tool tr is used. Additional separators for additional dimensions can be used in the same way.

Of course the performance of this approach is not very well, but if performance is not a criteria this approach is quite generic and can solve many problems:

array2d="1.1:1.2:1.3 2.1:2.2 3.1:3.2:3.3:3.4"

function process2ndDimension {
    for dimension2 in $*
    do
        echo -n $dimension2 "   "
    done
    echo
}

function process1stDimension {
    for dimension1 in $array2d
    do
        process2ndDimension `echo $dimension1 | tr : " "`
    done
}

process1stDimension

The output of that sample looks like this:

1.1     1.2     1.3     
2.1     2.2     
3.1     3.2     3.3     3.4