为什么$? -ne 0工作,但$? !=“0”不起作用?

时间:2015-12-30 17:50:25

标签: bash

我正在尝试简单检查最后一个表达式是否成功:

if [ $? -ne 0 ]; then
    chrome a.html
fi

这个表格有效。但是,当我尝试这样做时:

if [ $? != "0" ]; then
    chrome a.html
fi

或没有“”,它总是执行。我不确定为什么会这样,因为以下工作:

if [ $(id -u) != "0" ]; then
#You are not the superuser
echo "You must be superuser to run this" >&2
exit 1
fi

我会认为$?和$(id -u)都返回一个整数,因此比较!=“0”和-ne 0都应该工作。但是,似乎是$?与$(id -u)的类型不同。有什么解释吗?

2 个答案:

答案 0 :(得分:1)

我没有看到你描述的行为:

#!/bin/bash
false
echo false returns $?
false
if [ $? -ne 0 ] ; then
        echo 'testing return -ne 0'
fi

false
echo false returns $?
false
if [ $? != "0" ] ; then
        echo 'testing return != "0"'
fi

true
echo true returns $?
true
if [ $? != "0" ] ; then
        echo 'testing return != "0"'
fi
echo done
exit 0

的产率:

false returns 1
testing return -ne 0
false returns 1
testing return != "0"
true returns 0
done

答案 1 :(得分:0)

我相信这是因为$?以整数形式返回输出,但$(id -u)以字符串形式返回输出,而不是整数。 -ne运算符用于数字比较,而!=用于字符串比较。当您使用!=进行比较时,shell中的比较运算符不够智能,无法自动将字符串转换为整数。