Bad substitution error in zsh shell

arrayzsh

Hi in my previous question I got clarity on how to use associative arrays in zsh shell.

But whenever I trigger the following command in my script

for KEY in ${!array[@]} to iterate amongst the keys in my array

I get a bad substitution error.

even echo ${!array[@]} gives the same.

NB: array is the name of my associative array

Best Answer

zsh has different parameter substitution than Bash, which is documented in man zshexpn. It supports a variety of modifiers to expansion behaviour, which are put in parentheses before the variable name: ${(X)name}. The modifier to include array keys (including for associative arrays) is k: ${(k)array} expands to the list of keys in the array, except that if a key is the empty string, it is omitted. Use double quotes and the @ modifier to retain the empty key.

for x in "${(@k)array}" ; ...

will loop over the keys of the array array.

Related Question