Multidimensional associative arrays
Melkor333 opened this issue · 1 comments
Melkor333 commented
With bash version 4+ and associative arrays, it's possible to create multidimensional arrays. Here an example:
#written on phone and untested, apologies for mistakes!
declare -A animals
animalNames=()
addAnimal() {
animalNames+=("$1")
animals["$1_species"]="$2"
animals["$1_age"]="$3"
animals["$1_sound]="$4"
}
addAnimal Milo cat 8 meow
addAnimal Rex dog 2 woof
for animal in $animalNames; do
echo "$animal is a ${animals[$animal_species]}, it's ${animals[$animal_age]} years old and makes ${animals[$animal_sound]}!"
done
Would you be interested in adding this (and optionally some more helperfunctions) to the bible? I could create a PR in the next few weeks
james-crocker commented
Thanks for the example: Missing an ending " on
declare -A animals=()
declare -a animalNames=()
addAnimal() {
animalNames+=("$1")
animals["$1_species"]="$2"
animals["$1_age"]="$3"
animals["$1_sound"]="$4"
}
addAnimal Milo cat 8 meow
addAnimal Rex dog 2 woof
for animal in "${animalNames[@]}"; do
echo "$animal is a ${animals[${animal}_species]}, it's ${animals[${animal}_age]} years old and makes ${animals[${animal}_sound]}!"
done
Milo is a cat, it's 8 years old and makes meow!
Rex is a dog, it's 2 years old and makes woof!