ge 与 bash 中的双倍相等

ge vs double equal in bash

我正在尝试解决 hackerrank 练习。

If n is odd, print Weird
If n is even and in the inclusive range of 2 to 5, print Not Weird
If n is even and in the inclusive range of 6 to 20, print Weird
If n is even and greater than 20, print Not Weird

我的代码如下:

read n
if [ $n%2==0 ]; then
    if [ $n -ge 6 ] && [ $n -le 20 ]; then
        echo "Weird"
    else
        echo "Not Weird"
    fi
else
    echo "Weird"
fi

当我输入 3 时,我得到的结果是 Not Weird,这与 1 不正确,我觉得不奇怪。但是,当我尝试这样做时:

read n
if [ $(($n%2)) -eq 0 ]; then
    if [ $n -ge 6 ] && [ $n -le 20 ]; then
        echo "Weird"
    else
        echo "Not Weird"
    fi
else
    echo "Weird"
fi

我得到了正确的结果。有什么区别?

对于 if-else 内的真值评估,bash 提供 ((..)) 运算符,无需在前面使用 $

n=5
if (( (n % 2) == 0 )); then
    echo "Something"
    if (( n >= 6 )) && (( n <= 20 )); then
        echo "Some other thing"
    else
        echo "Other else thing"
    fi
else
    echo "Something else"
fi

阅读 here 了解更多信息。

[ ](或test)内置:

==,或者 POSIX 兼容 =,做一个 string 比较

-eq 进行数值比较

注:==-eq(以及其他比较)是参数[命令,所以它们必须以空格分隔,所以$n%2==0无效。

[[ ]] 关键词:

[ 一样,只是它进行模式匹配。作为关键字而不是内置函数,使用 [[ 的扩展在扫描的早期完成。

(( )) 语法

let 内置函数一样执行算术计算。空格分隔符不是强制性的。使用前导 $ 扩展变量不是必需的,也不推荐使用,因为它会改变扩展顺序。