Open Melkor333 opened 5 years ago
Thanks for the example: Missing an ending " on $1_sound and the key vars need ${animals[${adminal}_species|age|sound} as '$animal_xyz' is literal. Here is your example with fixes and works nice in Bash 4+
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!
With bash version 4+ and associative arrays, it's possible to create multidimensional arrays. Here an example:
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 :relaxed: