Skip to content

Instantly share code, notes, and snippets.

@kudosqujo
Last active April 9, 2020 00:39
Show Gist options
  • Select an option

  • Save kudosqujo/d92bda5031940e364d5f2443562ea7e5 to your computer and use it in GitHub Desktop.

Select an option

Save kudosqujo/d92bda5031940e364d5f2443562ea7e5 to your computer and use it in GitHub Desktop.
Define Hash Tables in Bash #bash
#!/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}"
}
#!/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