虽然shell脚本中的循环不能在linux bash shell中运行

时间:2016-11-04 00:57:03

标签: linux shell csh

在linux中编写shell脚本时有点新手。它是一个csh脚本,但我在bash shell中运行它,因为我使用#!/bin/bash代替#!/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

**注意:**数字只是为行编号。

上面的代码给出了输出错误:

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

即使它回显it starts并且错误中没有指定第9行,我也无法弄清楚出了什么问题。

2 个答案:

答案 0 :(得分:2)

必须将shebang设置为应该解释脚本的shell。从哪个shell运行脚本无关紧要。唯一重要的是脚本编写的语言。

您的脚本是用csh编写的,因此必须有shebang #!/bin/csh。即使您想从bash运行它也是如此。此外,您错过了签名中的空格:

$ 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

答案 1 :(得分:0)

试试这个:

#!/bin/bash
echo it starts

i=1
while [ $i -le 5 ]; do
  echo i is $i
  i=$(( i+1 ))
done

示例输出:

it starts
i is 1
i is 2
i is 3
i is 4
i is 5

这是一个很好的参考:

BASH Programming - Introduction HOW-TO

相关问题