Why does this code throw an error when passed to `zsh -n` but not to `zsh`?

zsh

Solution

You can see what's going on by adding the debug mode (`-x`)

As the non_exec mode (`-n`) doesn't execute nothing, it doesn't execute the `typeset` so `bar` is not an "associative array", and the assignment is not valid.

I see that the presence of the "rubbish" line (or other line looking like a command) prevents the program entering in the 'for' loop.

Zsh mailing list: zsh -n doesn't grok associate array indexes? (Jan 2011)

I tried with zsh 4.3.12 and the behaviour is more consistent, with `-n` the program never enters the 'for' loop.

For a smaller program with no loop:

#!/usr/bin/env zsh
typeset -A bar
bar[test]=testons
echo $bar

zsh 4.3.10 and 4.3.12 will both execute the program the same way, but `zsh-4.3.10 -n` will wrongly report an error (assignment to invalid subscript range) when `zsh-4.3.12 -n` will not.

As a conclusion, use zsh 4.3.12 (or newer, i discover that ZSH 5 is available) News about zsh (Including "news" from 1997!)

Problem

I'm trying in this example to copy all values from one associative array to another. I'm checking my code against syntax errors using `zsh -n` but this one throws a `test:12: bar: assignment to invalid subscript range`. ``` #!/usr/bin/env zsh typeset -A foo bar foo=( Adama "Commander" Tigh "Executive Officer" Roslin "President" ) bar=() for i in ${(k)foo}; do # "rubbish" bar[$i]=$foo[$i] done ``` If I uncomment the `# "rubbish` line, `zsh -n` stops complaining. Is there something wrong with my code or with `zsh -n` ?

Original source