I have noticed there are two alternative ways of building loops in zsh:
for x (1 2 3); do echo $x; done
for x in 1 2 3; do echo $x; done
They both print:
1
2
3
My question is, why the two syntaxes? Is $x
iterating through a different type of object in each of them?
Does bash make a similar distinction?
Addendum:
Why does the following work?:
#!/bin/zsh
a=1
b=2
c=5
d=(a b c)
for x in $d; do print $x;done
but this one doesn't?:
#!/bin/zsh
a=1
b=2
c=5
d=(a b c)
# It complains with "parse error near `$d'"
for x $d; do print $x;done
Best Answer
Several forms of complex commands such as loops have alternate forms in zsh. These forms are mostly inspired by the C shell, which was fairly common when zsh was young but has now disappeared. These alternate forms act exactly like the normal forms, they're just a different syntax. They're slightly shorter, but less clear.
The standard form for the
for
command isfor x in 1 2 3; do echo $x; done
, and the standard form for thewhile
command iswhile test …; do somecommand; done
. Ksh, bash and zsh have an alternate form offor
:for ((i = 0; i < 42; i++)); do somecommand; done
, which mimics thefor
loops of languages like Pascal or C, to enumerate integers. Other exotic forms that exist in zsh are specific to zsh (but often inspired by csh).