Zsh: append an element a dynamically-named associative array

Viewed 221

I have several associative arrays,

typeset -A first
typeset -A second
# …

and want to add an element (e.g. [a]=b) to one of them, but cannot find the right syntax. Started at

if something; then
  arr=first
else
  arr=second
fi

$arr[a]+=b # bad
$arr+=([a]=b) # bad

and have tried many mixes of quotation marks, braces, various subscripts and parameter expansion flags, arr=$first/arr=$second, etc. Everything I've tried is an error. Can it be done?

2 Answers

I don't think this is ideal but it should get the job done.

export "${arr}[a]"=b

This should also work in many cases:

eval "${arr}[a]=b"

eval has a bad reputation (often deservedly so), but with simple substitutions like those being used here, it should be fine.

Related