Weird difference in script execution

Hi,

So I have a very simple script which loops over 5 times and prints the iterator value.

#!/bin/sh
START=1
END=5
for i in $(eval echo "{$START..$END}")
do
        echo "$i"
done

If I save this script in a .sh file and run it in the terminal, the output I get is

{1..5}

But if I paste the same code in a terminal, I get the following

1
2
3
4
5

The second one is the expected output, but why is the first case not working as I expect?

I'm totally puzzled. Under cygwin the same code executes okay, but not in a unix shell..:confused:

Thanks.

Make sure you run it with bash or any recent shell instead of sh (in your shebang)...

1 Like

Do you mean it works in the terminal as well as in script under cygwin? If yes, then there's a simple explanation for that: In cygwin /bin/sh is actually bash (https://cygwin.com/faq/faq.html\#faq.using.shell-scripts\).

Well, most likely /bin/sh there is in fact the good ol' bourne shell, which does not support the {$START..$END} bash feature. If you have bash installed there, you could simply change the shebang line from #!/bin/sh to #!/bin/bash and it should work. If not, you'll have to write a more portable code, try:

#!/bin/sh

START=1
END=5
while [ $START -le $END ]
do
 echo $START
 START=`expr $START + 1`
done

This should work at least with bash, sh and ksh.

1 Like

On cygwin if you want a good shell to test bourne shell script try ash or dash

1 Like

What is the exact operating system are you on when this occurs?