Last active
April 9, 2020 00:39
-
-
Save kudosqujo/d92bda5031940e364d5f2443562ea7e5 to your computer and use it in GitHub Desktop.
Define Hash Tables in Bash #bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| # Assumes you are running with Bash 3 | |
| # {see: https://stackoverflow.com/questions/1494178/how-to-define-hash-tables-in-bash} | |
| # First, indirection. | |
| animals_moo=cow; sound=moo; i="animals_$sound"; echo "${!i}" | |
| # Secondly, `declare`: | |
| sound=moo; animal=cow; declare "animals_$sound=$animal"; echo "$animals_moo | |
| # Bring them together | |
| # Set a value: | |
| declare "array_$index=$value" | |
| # Get a value: | |
| arrayGet() { | |
| local array=$1 index=$2 | |
| local i="${array}_$index" | |
| printf '%s' "${!i}" | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| # Assumes your are running with Bash 4 | |
| # {see: https://stackoverflow.com/questions/1494178/how-to-define-hash-tables-in-bash} | |
| declare -A animals | |
| # You can fill it up with elements using the normal arry assignment operator. | |
| # For example, if you want to have a map of `animal[sound(key)] = animal(value)`: | |
| animals=( animals["moo"]="cow" ["woof"]="dog") | |
| # Or merge them: | |
| # declare -A animals=( animals["moo"]="cow" ["woof"]="dog") | |
| # Then use them just like normal arrays. Use | |
| # * `animals['key']='value'` to set value | |
| # * `"${animals[@]}"` to expand the values | |
| # * `"${!animals[@]}"` (notice the `!`) to expand the keys | |
| # Don't forget to quote them: | |
| echo "${animals[@]}" | |
| for sound in "${!animals[@]}"; do echo "$sound - ${animals[$sound]}"; done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment