ZSH for loop array variable issue
Solution 1
It's actually much simpler than that:
lw=('plugin1' 'plugin2' 'plugin3')
for i in $lw; do
. ~/Library/Rogall/plugins/$i/lw.prg end
done
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
Solution 2
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 end
done
Note that for this to work in zsh, you need to make zsh do the right thing with: set -o shwordsplit
Solution 3
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
1
2
3
4
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; done
1
2
3
4
user1296965
Updated on October 15, 2021Comments
-
user1296965 over 2 years
I'm working in zsh, but I'm sure that bash instructions will also be helpful.
I need to have a for loop that goes through the values stored in the array
lw
and then launches a shell script, based on the name value stored in the array.So far, this is what I've come up with:
$lw=('plugin1' 'plugin2' 'plugin3') for i in $lw; do . ~/Library/Rogall/plugins/$lw[$i]/lw.prg end; done
Running this gives me an error saying that it can't find
~/Library/Rogall/plugins//lw.prg
. It appears as if it's ignoring my variable all together.Any ideas where I've messed up?