我无法想出正确的分号和/或大括号组合。我想这样做,但作为命令行的单行代码:
while [ 1 ]
do
foo
sleep 2
done
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
在 while 的情况下也可以使用 sleep 命令。使单线看起来更干净恕我直言。
while sleep 2; do echo thinking; done
冒号总是“真”:
while :; do foo; sleep 2; done
您可以使用分号来分隔语句:
$ 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
一个非常简单的无限循环.. :)
while true ; do continue ; done
你的问题是:
while true; do foo ; sleep 2 ; done
对于简单的过程观察watch
使用
使用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;
我喜欢只在 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
如果您希望 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;
如果我能举两个实际的例子(有点“情感”)。
这会将所有以“.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
只是想做出贡献。
你甚至不需要使用do
and done
。对于无限循环,我发现for
与花括号一起使用更具可读性。例如:
for ((;;)) { date ; sleep 1 ; }
这适用于bash
和zsh
。不工作sh
。
你也可以试试这个警告:你不应该这样做,但因为问题是要求无限循环......这就是你可以做到的。
while [[ 0 -ne 1 ]]; do echo "it's looping"; sleep 2; done
您还可以将该循环放在后台(例如,当您需要与远程机器断开连接时)
nohup bash -c "while true; do aws s3 sync xml s3://bucket-name/xml --profile=s3-profile-name; sleep 3600; done &"