对bash算术比较感到困惑

时间:2016-01-04 13:44:41

标签: bash

我已经看到了关于bash整数检查和比较的其他答案,但是我得到的结果对我来说非常混乱。 假设我有这个脚本:

if [[ $1 -eq $1 ]] ;then
  echo "number"
else
  echo "not number"
fi

if (( $1 >= 0 )) ;then
  echo "number"
else
  echo "not number"
fi

如果我为参数1传递一个字符串,我会回到“数字”。

1 个答案:

答案 0 :(得分:2)

那是因为字符串被理解为值为0的变量,0 >= 0为真。尝试使用>(但会将0报告为not number - 但它已将所有负整数错误分类。)

比照:

a=1
b=a
x=b
(( x > 0 )) && echo 1
a=0
(( x > 0 )) || echo 0

甚至

$ a=x
$ x=a
$ (( x > 0 ))
bash: ((: a: expression recursion level exceeded (error token is "a")

Bash努力解决变量:

(
    for l in a{1..1023} ; do
        printf "$l\n$l="
    done
    echo 1
    echo '((a1>0))'
) | tail -n+2 | bash
相关问题