754

我无法想出正确的分号和/或大括号组合。我想这样做,但作为命令行的单行代码:

while [ 1 ]
do
    foo
    sleep 2
done
4

14 回答 14

1452
while true; do foo; sleep 2; done

顺便说一句,如果您在命令提示符下将其键入为多行(如您所显示的那样),然后使用向上箭头调用历史记录,您将在单行上得到正确的标点。

$ while true
> do
>    echo "hello"
>    sleep 2
> done
hello
hello
hello
^C
$ <arrow up> while true; do    echo "hello";    sleep 2; done
于 2009-08-17T16:32:32.533 回答
194

在 while 的情况下也可以使用 sleep 命令。使单线看起来更干净恕我直言。

while sleep 2; do echo thinking; done
于 2012-11-02T10:53:11.617 回答
78

冒号总是“真”:

while :; do foo; sleep 2; done
于 2012-11-06T13:35:49.557 回答
44

您可以使用分号来分隔语句:

$ while [ 1 ]; do foo; sleep 2; done
于 2009-08-17T16:32:41.237 回答
32

您还可以使用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
于 2013-08-25T12:49:30.503 回答
14

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

while true ; do continue ; done

你的问题是:

while true; do foo ; sleep 2 ; done
于 2015-07-09T05:44:04.363 回答
12

对于简单的过程观察watch使用

于 2016-12-14T11:35:13.527 回答
12

使用while

while true; do echo 'while'; sleep 2s; done

使用for循环:

for ((;;)); do echo 'forloop'; sleep 2; done

使用Recursion, (与上面有点不同,键盘中断不会停止它)

list(){ echo 'recursion'; sleep 2; list; } && list;
于 2019-05-26T04:25:16.920 回答
9

我喜欢只在 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
于 2011-01-29T10:43:48.297 回答
7

如果您希望 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;
于 2017-05-16T06:50:11.623 回答
2

如果我能举两个实际的例子(有点“情感”)。

这会将所有以“.jpg”结尾的文件的名称写入文件夹“img”中:

for f in *; do if [ "${f#*.}" == 'jpg' ]; then echo $f; fi; done

这将删除它们:

for f in *; do if [ "${f#*.}" == 'jpg' ]; then rm -r $f; fi; done

只是想做出贡献。

于 2011-07-02T16:32:48.597 回答
2

你甚至不需要使用doand done。对于无限循环,我发现for与花括号一起使用更具可读性。例如:

for ((;;)) { date ; sleep 1 ; }

这适用于bashzsh。不工作sh

于 2020-11-25T10:26:21.470 回答
2

你也可以试试这个警告:你不应该这样做,但因为问题是要求无限循环......这就是你可以做到的。

while [[ 0 -ne 1 ]]; do echo "it's looping";   sleep 2; done
于 2017-02-07T20:47:56.883 回答
1

您还可以将该循环放在后台(例如,当您需要与远程机器断开连接时)

nohup bash -c "while true; do aws s3 sync xml s3://bucket-name/xml --profile=s3-profile-name; sleep 3600; done &"
于 2021-06-15T18:57:39.830 回答