dylanaraps / pure-bash-bible

📖 A collection of pure bash alternatives to external processes.
MIT License
36.32k stars 3.25k forks source link

Multidimensional associative arrays #41

Open Melkor333 opened 5 years ago

Melkor333 commented 5 years ago

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 :relaxed:

james-crocker commented 4 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!