关于bash:为什么空循环在Shell脚本中无效?

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

如果您的系统不支持它,请以较大的间隔使用sleep

1
while :; do sleep 86400; done

注意:

  • 使用while :代替while true可能/将删除不必要的fork,具体取决于true的实现方式(内置在Shell中,还是作为独立的应用程序)。

您正在尝试实现繁忙循环,请不要执行此操作。

繁忙的循环将:

  • 无用地使用100%CPU
  • 防止其他任务占用CPU时间
  • 降低整个系统的感知性能
  • 使用多余的功率,尤其是在支持动态频率缩放的系统上

Why is an empty loop invalid in shell script?

因为它是... bashwhile循环的格式如下:

1
while list-1; do list-2; done

如果不提供list-2,则说明您没有正确格式化的while循环。

正如其他人指出的那样,请使用noop(:)或其他任何方法来满足list-2

:记录如下:

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源代码中进行挖掘,则可以发现它如何解析while loop

1
2
shell_command:  ...
    |   WHILE compound_list DO compound_list DONE

如果检查compound_list的定义,您会看到它必须至少包含一个shell指令;它不能为空。

除非您想加热CPU并耗尽电池,否则没有理由编写空(无限)循环。那就是为什么Bash禁止空循环的原因。

正如其他人所述,您可以使用true:(后者是前者的别名):

1
2
while true; do true; done
while :; do :; done


在其手册页中再次使用true:true-成功执行任何操作

1
while true; do true; done