Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在bash中ge与double相等_Bash_Operators - Fatal编程技术网

在bash中ge与double相等

在bash中ge与double相等,bash,operators,Bash,Operators,我正在尝试解决一个黑客程序 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 ]

我正在尝试解决一个黑客程序

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
的形式输入时,得到的结果是
不奇怪
,这与
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
n=5
如果(((n%2)==0));然后
呼应“某物”

如果((n>=6))和((n
[
]
(或
测试
)内置:

=
,或者为了兼容POSIX,执行字符串比较

-eq
进行数值比较

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

[[
]
关键字:

[
相同,只是它进行模式匹配。作为关键字而不是内置项,使用
[[
进行扩展将在扫描之前完成

((
语法


使用
let
内置函数执行算术求值。不强制使用空格分隔符。不需要使用前导的
$
展开变量,因为它会更改展开顺序。请发布您的目标是什么?使用示例输入文件和预期的示例输出。为什么你会使用
$(…)
在其中一个中执行数学运算,而不是在另一个中执行数学运算吗?此外,你需要在
==
周围使用空格,就像你在
-eq
[$((n%2))==0]
周围使用空格一样(虽然不建议使用空格,但只要
$((n%2))的结果有效)
是文本字符串
0
,而不是
00
或表示0的其他字符串).
=
是字符串比较的运算符。
-eq
是整数比较的运算符。
-ge
的意思是
大于或等于
,因此根本不是一回事。在每个示例中,如果
,您可以将两种情况简化为第一种情况-其余的代码只会使问题更难回答ead.其他相关差异:
[]
不计算数值表达式(例如,
$n%2
);
[[[]]]
如果它们是数值比较的操作数,例如
-eq
(())
总是计算。此外,在
[]
中,
=
是(字符串)比较,
=
可能是同义词;在
[[]]
它们都是字符串比较,而在
(())
中,
==
是数值比较,
=
是变量赋值。