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

while [ 1 ]
do
    foo
    sleep 2
done

当前回答

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

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

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

其他回答

使用while:

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

用于循环:

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

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

list(){ echo 'recursion'; sleep 2; list; } && list;

您还可以使用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

冒号总是“true”:

while :; 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

对于简单的过程监视,请改用监视