Bash – For loops in zsh and bash

bashzsh

I have noticed there are two alternative ways of building loops in zsh:

  1. for x (1 2 3); do echo $x; done
  2. 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 is for x in 1 2 3; do echo $x; done, and the standard form for the while command is while test …; do somecommand; done. Ksh, bash and zsh have an alternate form of for: for ((i = 0; i < 42; i++)); do somecommand; done, which mimics the for 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).

Related Question