Map in Bash

Declare Map
declare -A mymap

mymap["key1"]="value1"
mymap["key2"]="value2"
mymap["key3"]="value3"

echo ${mymap["key2"]}

The command declare -A mymap is used to declare an associative array in Bash. The -A option is used to specify that the variable mymap is an associative array.

An associative array is a type of array in Bash that uses strings as indexes instead of numbers. In this case, mymap is an associative array that will store key-value pairs. The keys in this array are the strings "key1", "key2", and "key3", and the corresponding values are "value1", "value2", and "value3", respectively. #chatgpt

Iterate over the map
declare -A mymap

mymap["key1"]="value1"
mymap["key2"]="value2"
mymap["key3"]="value3"

# Iterate over the keys of the associative array
for key in "${!mymap[@]}"; do
  echo "Key: $key, Value: ${mymap[$key]}"
done

Check if map has value
map.does_key_exist() {
  local -n map_ref="$1"
  local key="${2:?Key is required}"

  # Check if the variable is an associative array
  if [[ -v map_ref["$key"] ]]; then
      if [[ -n "${map_ref["$key"]}" ]]; then
          echo.log "The key '$key' exists with value: '${map_ref["$key"]}'"
          return 0
      else
          echo.log "The key '$key' exists, but the value is empty."
          return 1
      fi
  else
      echo.log "The key '$key' does not exist in the map."
      return 1
  fi
}
export -f map.does_key_exist

Consider using JSON instead

Note: if you are using MAPs in bash consider using JSON with jq instead.

  • JSON with jq will allow:
    • multi values per key/complex values per key.
    • allow values be read/created by other languages/tools.

There is also an added benefit of being practicing JSON data manipulation.

CONs

  • The main CON of this approach is speed, timing showed about 15ms cost for running echo.eg.json | jq . msg.
    • Can be remedied with abstracting in to a function call and later compiling JSON into shell.
  • Another CON is navigation
    • Can be remedied with additional tooling but does require additional tooling add on.