为什么shell脚本中的空循环无效?

Stu*_*ent 4 bash shell loops

我想让我的shell脚本无限地等待,并认为下面的代码会这样做.

#!/bin/bash
while true
do
done
Run Code Online (Sandbox Code Playgroud)

但是,上面的脚本报告语法错误.

./Infinite_Loop.sh:第4行:意外令牌"完成"附近的语法错误

./Infinite_Loop.sh:第4行:"完成"

与编程语言不同,为什么shell脚本期望循环中至少有一个语句?

cri*_*riw 8

另一种选择是设置一个 NOP(无操作),基本上什么都不做。

在 bash 中,NOP 的等价物是:.

while true; do
  :
done
Run Code Online (Sandbox Code Playgroud)


Att*_*tie 7

我想让我的shell脚本无限期地等待

如果您的系统支持它,请使用:

sleep infinity
Run Code Online (Sandbox Code Playgroud)

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

while :; do sleep 86400; done
Run Code Online (Sandbox Code Playgroud)

注意:

  • 使用while :代替while truemay /将删除不必要的fork,取决于如何true实现(内置到shell中,或作为独立的应用程序).

您正在尝试实现繁忙的循环,不要这样做.

繁忙的循环将:

  • 使用100%CPU没有用处
  • 防止其他任务获得CPU时间
  • 降低整个系统的感知性能
  • 使用超出必要的功率,尤其是支持动态频率调整的系统

为什么shell脚本中的空循环无效?

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

while list-1; do list-2; done
Run Code Online (Sandbox Code Playgroud)

如果您不提供list-2,那么您没有正确格式化的while循环.

正如其他人所指出的,使用noop(:)或其他任何东西来满足list-2.

: 记录如下:

: [arguments]
    No effect; the command does nothing beyond expanding arguments and performing any
    specified redirections.  A zero exit code is returned.
Run Code Online (Sandbox Code Playgroud)