For loop

i executed below command on my cmd

for i in {1..8}; do echo n; done

given me

n
n
n
n
n
n
n
n

But while I am trying to execute same thing putting in file say test.sh and running sh test.sh

its giving me only

n

Can someone explain why?

What operating system are you using?

What is your login shell?

What happens if you run test.sh with your login shell instead of running it with sh ?

Hi Don

piyush@L-6PSWH32:~$ ./test.sh
n
n
n
n
n
n
n
n
piyush@L-6PSWH32:~$ sh test.sh
n
piyush@L-6PSWH32:~$ echo $SHELL
/bin/bash
piyush@L-6PSWH32:~$

Your shell is bash, your script runs using plain sh, which doesn't have bash features like {1..8}

great...

thanks a lot Corona

To expand on what Corona wrote, running with the Bourne shell sh, your loop (failing to understand {1..8} as it is a bash expression giving boundaries) will use it as a single term.
First time through, variable $i will be the literal string {1..8} and your loop will run (displaying an n )
When the loop hits the done and tries again, there are no other items in the list to process, so the loop ends.

You can see this effect by displaying the value of $i from within the loop and then try it both ways.

I hope that this helps,
Robin

Or test with echo

echo {1..8}

This expands to 1 2 3 4 5 6 7 8 in bash only.
A portable loop needs

for i in 1 2 3 4 5 6 7 8