About Me


Articles

Nested associative Arrays

This articel describes one of the lesser known features of the kornshell 93, nested associative Arrays.

Let's say, you want to represent the contents of an INI-style file as a shell variable. The first index should hold the section names and the second one the key names.

If you can define all the entries in one statement, you can write

ini=(
    ['section 1']=(
        ['key 1']='entry 1/1'
        ['key 4']='entry 1/4'
        ['key 7']='entry 1/7'
    )
    ['section 2']=(
        ['key 2']='entry 2/2'
        ['key 5']='entry 2/5'
        ['key 8']='entry 2/8'
    )
    ['section 3']=(
        ['key 1']='entry 3/1'
        ['key 4']='entry 3/4'
        ['key 8']='entry 3/8'
    )
)

But most of the time you will have to build the array step by step. In this case you can write

typeset -A ini=()
 
typeset -A ini['section 1']=()
ini['section 1']['key 1']='entry 1/1'
ini['section 1']['key 4']='entry 1/4'
ini['section 1']['key 7']='entry 1/7'
 
typeset -A ini['section 2']=()
ini['section 2']['key 2']='entry 2/2'
ini['section 2']['key 5']='entry 2/5'
ini['section 2']['key 8']='entry 2/8'
 
typeset -A ini['section 3']=()
ini['section 3']['key 1']='entry 3/1'
ini['section 3']['key 4']='entry 3/4'
ini['section 3']['key 8']='entry 3/8'

In both cases you get identical variables ini.

To access a specific value of the array you can write

${ini[$section][$key]}

To enumerate all values of the first index, use

"${!ini[@]}

To enumerate all values of the second index for a given first index $section, write

${!ini[$section][@]}

This is used in the following code to dump the entire array to stdout:

for section in "${!ini[@]}"
do
    for key in "${!ini[$section][@]}"
    do
        print -r -- "ini[$section][$key] = ${ini[$section][$key]}"
    done
done

which produces the following output

ini[section 1][key 1] = entry 1/1
ini[section 1][key 4] = entry 1/4
ini[section 1][key 7] = entry 1/7
ini[section 2][key 2] = entry 2/2
ini[section 2][key 5] = entry 2/5
ini[section 2][key 8] = entry 2/8
ini[section 3][key 1] = entry 3/1
ini[section 3][key 4] = entry 3/4
ini[section 3][key 8] = entry 3/8

To use this feature, you need at least ksh93t. The examples were tested with version 93t+ 2009-05-01 and 93u+ 2011-06-22.

Paul Herger

SCSA Zertifikat

 
knowhow/kornshell/nestedarrays.txt · Last modified: 2011/09/29 10:00 by Paul Herger
© Paul Herger