Can't test whether key exists in associative zsh array
Since the key x
is present in arr
, ${arr[(Ie)x]}
expands to the list of keys that match x
, which is just x
. This results in the arithmetic expression x
, which evaluates to the numerical value of x
. But x
is unset, hence the error that you see.
Generally, be careful with associative arrays in arithmetic expressions.
[[ $arr[(Ie)x] ]]
would work for a non-empty key. Alternatively, ((${+arr[x]}))
is more common, but I don't see any advantage to it: it also doesn't work with empty keys. I think that the $+
approach works for arbitrary keys if you use an intermediate variable:
key=x # or '' or ']' …
(($+arr[$key]))