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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With