首页 > 解决方案 > Bash 嵌套条件显示意外行为

问题描述

请看一下:这应该与 X10 相呼应,但与大奖相呼应……谁能明白为什么它的行为不正常?可能只是我犯的一些错误,不会引发错误?

dice1=1
dice2=40

#These two lines are just tests to see if my brain still function:
echo "Is dice 1 less than 2? $(($dice1 < 2))"
echo "Is dice 2 between 6 and 54? $(($dice2 > 5 && $dice2 < 55))"

if [[ $dice1 == 1 ]]
then
        if [[ $dice2 < 6 ]]
        then
                #dice1 has to be equal 1 and dice2 less than 6:
                echo "jackpot"
        else
                #Since dice2 is larger than 5, if smaller than 55
                #it should be between 6 and 54...
                if [[ $dice2 < 55 ]]
                then
                        echo "X10"
                else
                        echo "X5"
                fi
        fi
else
        echo "Dice one is not equal 1."
fi

标签: bash

解决方案


与 一起使用时[[<and>运算符使用当前语言环境按字典顺序排序。

我看到两个选项。

在算术上下文中进行比较:

if (( $dice1 == 1 ))
then
    if (( $dice2 < 6 ))

或老式的方式:

if [[ $dice1 -eq 1 ]]
then
    if [[ $dice2 -lt 6 ]]

推荐阅读