Sitelet https://web.archive.org/web/20200707041948/https://github.com/dylanaraps/pure-bash-bible/issues/41
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multidimensional associative arrays #41

Open
Melkor333 opened this issue Sep 22, 2018 · 1 comment
Open

Multidimensional associative arrays #41

Melkor333 opened this issue Sep 22, 2018 · 1 comment
Labels

Comments

@Melkor333
Copy link

@Melkor333 Melkor333 commented Sep 22, 2018

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
Copy link

@james-crocker james-crocker commented Mar 27, 2020

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
3 participants
You can’t perform that action at this time.