我想让我的shell脚本无限期地等待,并认为下面的代码会这样做。
#!/bin/bash
while true
do
done
但是,上面的脚本报告语法错误。
./ Infinite_Loop.sh:line 4:意外令牌“完成”附近的语法错误
./ Infinite_Loop.sh:line 4:`done'
与编程语言不同,为什么shell脚本期望循环中至少有一个语句?
答案 0 :(得分:7)
我想让我的shell脚本无限地等待
如果您的系统支持,请使用:
sleep infinity
如果您的系统不支持,请使用间隔较大的sleep
:
while :; do sleep 86400; done
注意:
while :
代替while true
可能/将删除不必要的fork
,具体取决于true
的实施方式(内置于shell中,或作为独立内容)应用程序)。您正在尝试实施繁忙的循环,不要这样做。
繁忙的循环将:
为什么shell脚本中的空循环无效?
因为它是...... while
中bash
循环的格式如下:
while list-1; do list-2; done
如果您没有提供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.
答案 1 :(得分:1)
再次使用true,从它的手册页:true - 什么也不做,成功
while true; do true; done
答案 2 :(得分:1)
另一种选择就是设置NOP(无操作),基本上什么都不做。
在bash中,NOP的等价物为:
。
while true; do
:
done
答案 3 :(得分:1)
这不是Bash语法的一部分。 manual告诉我们:
while命令的语法是:
while test-commands; do consequent-commands; done
事实上,如果你挖掘Bash源代码,你可以找到how it parses a while loop
:
shell_command: ...
| WHILE compound_list DO compound_list DONE
如果你检查compound_list
’s definition,你可以看到它必须包含至少一个shell指令;它不能是空的。
除非您想加热CPU并耗尽电池,否则没有理由编写空(无限)循环。这可能就是为什么Bash不允许空循环。
正如其他人所说,您可以使用true
或:
(the latter is an alias for the former):
while true; do true; done
while :; do :; done