Home > other >  Access associative arrays with variables
Access associative arrays with variables

Time:08-11

Let's say we declared two associative arrays:

#!/bin/bash

declare -A first
declare -A second

first=([ele]=value [elem]=valuee [element]=valueee)
second=([ele]=foo [elem]=fooo [element]=foooo)

# echo ${$1[$2]}

I want to echo the given hashmap and element from script inputs. For example, if I run sh.sh second elem, the script should echo fooo.

CodePudding user response:

An inelegant but bullet-proof solution would be to white-list $1 with the allowed values:

#!/bin/bash

# ...

[[ $2 ]] || exit 1

unset result
case $1 in
     first) [[ ${first["$2"] X}  ]] && result=${first["$2"]}  ;;
    second) [[ ${second["$2"] X} ]] && result=${second["$2"]} ;;
         *) exit 1 ;;
esac
[[ ${result X} ]] && printf '%s\n' "$result"

notes:

  • [[ $2 ]] || exit 1 because bash doesn't allow empty keys
  • [[ ${var X} ]] checks that the variable var is defined; with this expansion you can also check that an index or key is defined in an array.

CodePudding user response:

A couple ideas come to mind:

Variable indirection expansion

Per this answer:

arr="$1[$2]"              # build array reference from input fields
echo "${!arr}"            # indirect reference via the ! character

For the sample call sh.sh second elem this generates:

fooo

Nameref (declare -n) (requires bash 4.3 )

declare -n arr="$1"
echo "${arr[$2]}"

For the sample call sh.sh second elem this generates:

fooo
  • Related