我很难找到分号和/或大括号的正确组合。我想这样做,但作为命令行的一行代码:

while [ 1 ]
do
    foo
    sleep 2
done

当前回答

您还可以使用until命令:

until ((0)); do foo; sleep 2; done

注意,与while相反,只要测试条件具有不为零的退出状态,until就会在循环内执行命令。


使用while循环:

while read i; do foo; sleep 2; done < /dev/urandom

使用for循环:

for ((;;)); do foo; sleep 2; done

使用until的另一种方法:

until [ ]; do foo; sleep 2; done

其他回答

您还可以使用until命令:

until ((0)); do foo; sleep 2; done

注意,与while相反,只要测试条件具有不为零的退出状态,until就会在循环内执行命令。


使用while循环:

while read i; do foo; sleep 2; done < /dev/urandom

使用for循环:

for ((;;)); do foo; sleep 2; done

使用until的另一种方法:

until [ ]; do foo; sleep 2; done

在while的情况下也可以使用sleep命令。让一个内胆看起来更干净。

while sleep 2; do echo thinking; done

如果您希望while循环在某个条件后停止,并且当满足该条件时,foo命令返回非零,则可以让循环像这样中断:

while foo; do echo 'sleeping...'; sleep 5; done;

例如,如果foo命令正在批量删除内容,并且当没有剩余内容可删除时返回1。

如果您有一个自定义脚本,需要多次运行一个命令,直到出现某种情况,那么这很好。编写脚本以在满足条件时以1退出,在再次运行时以0退出。

例如,假设您有一个python脚本batch_update.py,它更新数据库中的100行,如果有更多行需要更新,则返回0,如果没有更多行,则返回1。以下命令将允许您一次更新行100,并在更新之间休眠5秒:

while batch_update.py; do echo 'sleeping...'; sleep 5; done;

非常简单的无限循环..:)

while true ; do continue ; done

你的问题是:

while true; do foo ; sleep 2 ; done

我只喜欢在WHILE语句中使用分号,和&&运算符使循环做多件事。。。

所以我总是这样做

while true ; do echo Launching Spaceship into orbit && sleep 5s && /usr/bin/launch-mechanism && echo Launching in T-5 && sleep 1s && echo T-4 && sleep 1s && echo T-3 && sleep 1s && echo T-2 && sleep 1s && echo T-1 && sleep 1s && echo liftoff ; done