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

while [ 1 ]
do
    foo
    sleep 2
done

当前回答

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

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

其他回答

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

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

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

只是想做出贡献。

您还可以使用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 [[ 0 -ne 1 ]]; do echo "it's looping";   sleep 2; done

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

while sleep 2; do echo thinking; done

你甚至不需要使用do and done。对于无限循环,我发现使用大括号更容易理解。例如:

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

这在bash和zsh中有效。在sh。