如何在Unix / Linux操作系统的shell脚本中创建无限循环?

无限循环用于运行一组永无休止的重复指令。在这个过程中,我们创建了一个无限循环的循环,并继续执行指令,直到外部强制停止。
Bash无限While循环
在这种情况下,哪个循环是最佳选择。以下语法用于在Shell脚本中创建无限while循环。
循环示例:
#!/usr/bin/env bash

while :
do
echo "Press [CTRL+C] to exit this loop..."
# Add more instructions here
sleep 2
done
您还可以使用带有while循环的Unix true命令来无休止地运行它。使用true命令的while循环语法将类似于以下示例。
循环示例:
#!/usr/bin/env bash

while true
do
echo "Press [CTRL+C] to exit this loop..."
# Add more instructions here
sleep 2
done
在无限循环中添加现有指令
有时您可能需要根据条件从永无止境的循环中退出。如果满足特定条件,并且您希望该无限循环在该条件上中断。
#!/usr/bin/env bash

while true
do
echo "Press [CTRL+C] to exit this loop..."
# Add more instructions here
sleep 2

if [ condition ]
then
break
fi
done
在上面的循环中添加一个if语句以中断匹配条件。

A5互联https://www.a5idc.net/

原文地址:https://www.cnblogs.com/a5idc/p/13540218.html