当条件满足时,循环不会结束

当条件满足时,循环不会结束

我正在尝试制作一个在 bash 中运行的赛马博彩游戏,
我将 gpio 库从 raspbian 复制到 ubuntu,当 $BET 不为 0 时,while 循环不会结束

BET=0
while [ $BET=0 ]
do
    if [ $(gpio read 21) -eq 1 ]
        then
            BET=1
    elif [ $(gpio read 22) -eq 1 ]
        then
            BET=2
    elif [ $(gpio read 23) -eq 1 ]
        then
            BET=3
    elif [ $(gpio read 24) -eq 1 ]
        then
            BET=4 
    elif [ $(gpio read 25) -eq 1 ]
        then
            BET=5
    else
        echo "" > /dev/null 
    fi
    echo $BET
done

为什么这不起作用?提前致谢

答案1

您缺少一些空格:[ $BET=0 ]应该[ $BET = 0 ]改为。更好的方法是,使用 进行数值比较[ $BET -eq 0 ]

看看man test三者之间的区别。

PS:Run shellcheck(来自同名包)可帮助您发现 shell 脚本中的潜在缺陷和问题。对于您的脚本,它会打印:

In - line 2:
while [ $BET=0 ]
        ^-- SC2077: You need spaces around the comparison operator.


In - line 4:
    if [ $(gpio read 21) -eq 1 ]
         ^-- SC2046: Quote this to prevent word splitting.


In - line 7:
    elif [ $(gpio read 22) -eq 1 ]
           ^-- SC2046: Quote this to prevent word splitting.


In - line 10:
    elif [ $(gpio read 23) -eq 1 ]
           ^-- SC2046: Quote this to prevent word splitting.


In - line 13:
    elif [ $(gpio read 24) -eq 1 ]
           ^-- SC2046: Quote this to prevent word splitting.


In - line 16:
    elif [ $(gpio read 25) -eq 1 ]
           ^-- SC2046: Quote this to prevent word splitting.

相关内容