0

I have very simple script(for_loop4.sh) as shown below.

# !/bin/zsh
#

for (( i = 0; i < 3; i++ ))
do
    echo $i;
done

I'm using zsh 5.0.7 for my shell.

When running this script using source, zsh and . command, it works as expected. But, when calling this script directly, it fails with the message "Bad for loop variable".

Why this happens ? What's difference ?

$ source ./for_loop4.sh
0
1
2

$ zsh ./for_loop4.sh
0
1
2

$ . ./for_loop4.sh
0
1
2

$ ./for_loop4.sh
./for_loop4.sh: 4: ./for_loop4.sh: Syntax error: Bad for loop variable
phuclv
  • 37,963
  • 15
  • 156
  • 475
John
  • 41
  • 6
  • Is the execute bit set on for_loop4.sh ? Does the system have the same results if you chmod +x ./for_loop.sh ? – vielmetti Jun 15 '16 at 04:23
  • I get different results on my Mac, which is running zsh 5.0.8. – vielmetti Jun 15 '16 at 04:24
  • 1
    Possible duplicate of [Syntax error: Bad for loop variable](http://stackoverflow.com/questions/30358065/syntax-error-bad-for-loop-variable) – xxfelixxx Jun 15 '16 at 04:26

2 Answers2

1

Your first line is wrong:

# !/bin/zsh

It should be:

#!/bin/zsh
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Thanks !! This fixes my problem. – John Jun 15 '16 at 05:30
  • Just for completeness: What happens with the wrong line is that the default shell - `/bin/sh` - is used. In this case `/bin/sh` does not seem to be a link to/a copy of `zsh` or `bash` (I am guessing `dash`) and does not support this type of `for`-loop. – Adaephon Jun 15 '16 at 23:39
0

Make sure that where is your zsh installed. It can be installed into /usr/ directory.
You can type,

$ which zsh