Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested dictionaries in bash

I saw it is possible to generate a dict using bash 4 :

declare -A dict=( ["John"]="23" ["Jackie"]="21" )

My question is can we assign another dictionary as value ?

For example having a structure like :

declare -A dict=( ["John"]=["age"="23" "weight"="150"] ["Jackie"]=["age"="21" "weight"="140"] )

Which would represents a structure like:

John:
    age: 23
    weight: 150


Jackie:
    age: 21
    weight: 140

I thought to use 2 dictionaries however I don't know if this is the best way to achieve nested dict in bash :

declare -A John=( ["age"]="23" ["weight"]="150" )
declare -A dict=( ["John"]=${John} )

In this case, I could not access age or weight variables.

Thanks

like image 749
syedelec Avatar asked Jun 19 '26 06:06

syedelec


1 Answers

Althought bash does not support nested arrays as others comment, if your bash version is 4.3 or newer, declare has an -n option to define a refence to the variable name which works as something like a C pointer.
Then you can say:

declare -A John=( ["age"]="23" ["weight"]="150" )
declare -A Jackie=( ["age"]="21" ["weight"]="140" )
declare -a dict=("John" "Jackie")

for member in "${dict[@]}"; do
    echo "$member :"
    declare -n p="$member"  # now p is a reference to a variable "$member"
    for attr in "${!p[@]}"; do
        echo "    $attr : ${p[$attr]}"
    done
done

The output:

John :
    weight : 150
    age : 23
Jackie :
    weight : 140
    age : 21

Note that the -n option is not a well-used function and has some limitations.

like image 165
tshiono Avatar answered Jun 22 '26 00:06

tshiono