zsh testing existence of a key in an associative array via indirect expansion
4
votes
4
answers
1635
views
So I know that you can test for the existence of a regular parameter via indirect expansion by doing something like:
foo=1
bar=foo
(( ${(P)+bar} )) && print "$bar exists"
And I know you can test for the existence of a key inside an associative array by doing something like:
foo=([abc]=1)
(( ${+foo[abc]} )) && print "abc exists"
However I can't figure out how to combine the two and test for the existence of a key inside an associative array via indirect expansion. Is this possible without using eval?
I tried several combinations including the following, and none of them worked:
foo=([abc]=1)
bar=foo
(( ${(P)+bar[abc]} )) && print "$bar has key abc" # Test fails
(( ${(P)+${bar}[abc]} )) && print "$bar has key abc" # Passes for nonexistant keys
(( ${${(P)+bar}[abc]} )) && print "$bar has key abc" # Test fails
(( ${${(P)bar}+[abc]} )) && print "$bar has key abc" # prints "zsh: bad output format specification"
Asked by Matt Wilder
(71 rep)
Jan 23, 2020, 11:52 PM
Last activity: Aug 7, 2021, 04:41 PM
Last activity: Aug 7, 2021, 04:41 PM