首页 > 解决方案 > 为什么在while和do之间有共同的回声线会在bash中创建一个死循环?

问题描述

while 循环将执行 3 次。

i=0
while [[ $i -lt 3 ]]
do
    echo "haha"
    ((i++))
done

输出:

haha
haha
haha

让我echo "i am here"在 while 和 do 之间添加一条线。

i=0
while [[ $i -lt 3 ]]
echo "i am here"
do
    echo "haha"
    ((i++))
done

为什么会变成死循环,永不停止,输出

i am here
haha

永远?

标签: bash

解决方案


看看--helpbash on while

bash.exe"-3.1$ help while
while: while COMMANDS; do COMMANDS; done
     Expand and execute COMMANDS as long as the final command in the
    `while' COMMANDS has an exit status of zero.

while在您的情况下,最后的命令是

echo "i am here"

它总是会成功执行,因为它不会失败。
在这种情况下,退出状态为零 - 始终。

比较https://www.gnu.org/software/bash/manual/html_node/Exit-Status.html

出于 shell 的目的,以零退出状态退出的命令已成功。

所以你已经编写了一个无限循环。


推荐阅读