Comment by ๐Ÿฆ wasolili

Re: "Name associative array after variable?"

In: s/bash

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?

๐Ÿฆ wasolili [flaired user]

2025-02-25 ยท 1 year ago

1 Later Comment

๐Ÿš€ asdf [OP] ยท 2025-03-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]}

Original Post

๐ŸŒ’ s/bash

๐Ÿš€ asdf:

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?

๐Ÿ’ฌ 2 comments ยท 1 like ยท 2025-02-21 ยท 1 year ago