Why is an empty loop invalid in shell script?
我想让我的shell脚本无限等待,并认为下面的代码可以做到。
1 2 3 4 | #!/bin/bash while true do done |
但是,以上脚本报告语法错误。
./Infinite_Loop.sh: line 4: syntax error near unexpected token `done'
./Infinite_Loop.sh: line 4: `done'
与编程语言不同,为什么shell脚本在循环中期望至少一个语句?
I wanted to make my shell script wait infinitely
如果您的系统支持,请使用:
1 | sleep infinity |
如果您的系统不支持它,请以较大的间隔使用
1 | while :; do sleep 86400; done |
注意:
-
使用
while : 代替while true 可能/将删除不必要的fork ,具体取决于true 的实现方式(内置在Shell中,还是作为独立的应用程序)。
您正在尝试实现繁忙循环,请不要执行此操作。
繁忙的循环将:
- 无用地使用100%CPU
- 防止其他任务占用CPU时间
- 降低整个系统的感知性能
- 使用多余的功率,尤其是在支持动态频率缩放的系统上
Why is an empty loop invalid in shell script?
因为它是...
1 | while list-1; do list-2; done |
如果不提供
正如其他人指出的那样,请使用noop(
1 2 3 | : [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned. |
另一种选择是设置NOP(无操作),这基本上是什么都不做。
在bash中,NOP的等效项是
1 2 3 | while true; do : done |
意大利不是Basha语法的一部分。该手册告诉我们:
The syntax of the while command is:
1 while test-commands; do consequent-commands; done
实际上,如果您在Bash源代码中进行挖掘,则可以发现它如何解析
1 2 | shell_command: ... | WHILE compound_list DO compound_list DONE |
如果检查
除非您想加热CPU并耗尽电池,否则没有理由编写空(无限)循环。那就是为什么Bash禁止空循环的原因。
正如其他人所述,您可以使用
1 2 | while true; do true; done while :; do :; done |
在其手册页中再次使用true:true-成功执行任何操作
1 | while true; do true; done |