Young Millie Young Millie - 28 days ago 11
Bash Question

While loop in shell script not working in the linux bash shell

Am kind of newbie in writing shell scripts in linux. Its a

csh
script but am running it in the
bash
shell that why I used
#!/bin/bash
instead of
#!/bin/csh
.

1 #!/bin/bash
2 set i = 1
3 echo it starts
4
5 while ($i <= 5)
6 echo i is $i
7 @ i= $i +1
8 end


**Note: ** The numbers are just to number the lines.

The above code gives me the output with error:


it starts
./me.csh: line 9: syntax error: unexpected end of file



I can't figure out what is wrong even though it echos
it starts
and there is no line number 9 as specified in the error.

Answer

The shebang must be set to the shell that should interpret the script. It doesn't matter which shell you run the script from. The only thing that matters is the language the script is written in.

Your script is written in csh, and must therefore have the shebang #!/bin/csh. This is true even if you want to run it from bash. Also, you were missing a space in your at-sign-ment:

$ cat me.csh
#!/bin/csh
set i = 1
echo it starts

while ($i <= 5)
        echo i is $i
        @ i = $i + 1
end

$ ./me.csh
it starts
i is 1
i is 2
i is 3
i is 4
i is 5
Comments