ZSH for loop array variable issue ZSH for loop array variable issue shell shell

ZSH for loop array variable issue


It's actually much simpler than that:

lw=('plugin1' 'plugin2' 'plugin3')for i in $lw; do  . ~/Library/Rogall/plugins/$i/lw.prg enddone

In summary:

  • Assign to foo, not $foo (the shell would try to expand $foo and assign to whatever it expands to; typically not useful)
  • Use the loop variable directly; it contains the array value rather than the index


Why bother using the array? This can be done in portable sh very easily:

lw='plugin1 plugin2 plugin3'for i in $lw;  do . ~/Library/Rogall/plugins/$i/lw.prg enddone

Note that for this to work in zsh, you need to make zsh do the right thing with: set -o shwordsplit


I had a problem where a loop like this one

for i in (1 2 3 4); do echo $i; done

was repeatedly not working as I wanted. I would get errors like zsh: unknown file attribute: 1, or outputs like

1 2 3 4

no matter how I re-contorted it, instead of my desired

1234

To get my desired behaviour I had to remove the in keyword from the loop definition

for i (1 2 3 4); do echo $i; done1234