简体   繁体   English

虽然 shell 脚本中的循环在 linux bash shell 中不起作用

[英]While loop in shell script not working in the linux bash shell

Am kind of newbie in writing shell scripts in linux.我是在 linux 中编写 shell 脚本的新手。 Its a csh script but am running it in the bash shell that why I used #!/bin/bash instead of #!/bin/csh .它是一个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

**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.我无法弄清楚出了什么问题,即使它响应it starts并且没有错误中指定的第 9 行。

The shebang must be set to the shell that should interpret the script. shebang 必须设置为解释脚本的 shell。 It doesn't matter which shell you run the script from.从哪个 shell 运行脚本并不重要。 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 .您的脚本是用csh编写的,因此必须具有 shebang #!/bin/csh This is true even if you want to run it from bash.即使您想从 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

Output:输出:

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

Try this:试试这个:

#!/bin/bash
echo it starts

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

Sample output:示例输出:

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

Here is a great reference:这是一个很好的参考:

BASH Programming - Introduction HOW-TO BASH 编程 - 介绍 HOW-TO

you should use Visual Studio Code with some extensions to check bash script syntax.您应该使用带有一些扩展的 Visual Studio Code 来检查 bash 脚本语法。 I use Vscode in Window 10 WSL2 to run bash script.我在 Window 10 WSL2 中使用 Vscode 来运行 bash 脚本。

change (...) to ((...)) to fix error syntax:将 (...) 更改为 ((...)) 以修复错误语法:

#!/bin/bash
a=5

while ((a > 0)); do
    echo "a = $a"
    a=$((a - 1))
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM