单行Bash无限while循环的语法

时间:2025-04-07 07:43:19

我在提出正确的分号和/或花括号组合时遇到麻烦。 我想这样做,但是作为命令行的单行代码:

while [ 1 ]
do
    foo
    sleep 2
done

#1楼

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

#2楼

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

$ while [ 1 ]; do foo; sleep 2; done

#3楼

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

while sleep 2; do echo thinking; done

#4楼

冒号始终是“ true”:

while :; do foo; sleep 2; done

#5楼

您还可以使用until命令:

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

请注意,与whileuntil测试条件的退出状态不为零whileuntil将在循环内执行命令。


使用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

#6楼

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

while true ; do continue ; done

如果您的问题是:

while true; do foo ; sleep 2 ; done

#7楼

为了观看过程简单,请使用watch


#8楼

您也可以尝试这样做。警告:您不应该这样做,但是由于问题是要求无限循环,这是您可以做到的。

while [[ 0 -ne 1 ]]; do echo "it's looping";   sleep 2; done

#9楼

如果您希望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;

#10楼

我喜欢只对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

#11楼

使用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;

#12楼

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

这会将所有以“ .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

只是想贡献。