Name associative array after variable?

I need to be able to do something like "Declare -A $var", $var["${key}"]="${value}", and echo "$var[${key}]". What would the correct syntax for this be?

Posted in: s/bash

๐Ÿš€ asdf

Feb 21 ยท 5 months ago ยท ๐Ÿ‘ ed

2 Comments โ†“

๐Ÿฆ wasolili [...] ยท Feb 25 at 00:19:

are you asking to name the key after a variable, something like:

declare -A array

array["$key"]="$value"

echo ${array["$key"]}

or are you asking for something else?

๐Ÿš€ asdf [OP] ยท Mar 01 at 12:19:

@wasolili sorry for taking so long to respond, I've been kinda busy + I already got an answer on Reddit so the post here didn't serve much of a purpose anymore.

To answer your question, the script I'm writing takes input, and I needed to use that input as the name of an array.

I couldn't just use "declare -A array" and then use "${array[${key}]}", because the input might be something other than the word "array". The solution I got from reddit was:

declare -A $var

declare -n ref=$var

ref[$key]=$value

echo ${ref[$key]}


Source