【问题标题】:Bash -eq and ==, what's the diff?Bash -eq 和 ==,有什么区别?
【发布时间】:2014-04-15 14:24:32
【问题描述】:

为什么会这样:

Output=$( tail --lines=1 $fileDiProva )
##[INFO]Output = "OK"

if [[ $Output == $OK ]]; then
    echo "OK"
else
    echo "No Match"
fi

这不是吗?

Output=$( tail --lines=1 $fileDiProva )
##[INFO]Output = "OK"

if [[ $Output -eq $OK ]]; then
    echo "OK"
else
    echo "No Match"
fi

有什么区别?? == 和 -eq 之间?

谢谢!

【问题讨论】:

  • -eq 用于数值比较,== 用于字符串比较。显然第二次会失败。
  • 整数比较是-eq。比较字符串是==
  • 阅读 bash 文档(info bash,如果您的系统有它)并搜索 -eq
  • 顺便说一句,== 是一个 bash 扩展——习惯于使用 = 将更容易为其他 shell 编写代码。 (当然,[[ 也是一个扩展,但它更明显;我看到很多人认为== 是唯一正确的字符串比较运算符,但事实并非如此)。

标签: linux bash


【解决方案1】:

-eq 是算术测试。

您正在比较字符串。

来自help test

Other operators:

  arg1 OP arg2   Arithmetic tests.  OP is one of -eq, -ne,
                 -lt, -le, -gt, or -ge.

当您使用 [[ 并使用 -eq 作为运算符时,shell 会尝试评估 LHS 和 RHS。下面的例子会解释它:

$ foo=something
+ foo=something
$ bar=other
+ bar=other
$ [[ $foo -eq $bar ]] && echo y
+ [[ something -eq other ]]
+ echo y
y
$ something=42
+ something=42
$ [[ $foo -eq $bar ]] && echo y
+ [[ something -eq other ]]
$ other=42
+ other=42
$ [[ $foo -eq $bar ]] && echo y
+ [[ something -eq other ]]
+ echo y
y

【讨论】:

  • 没有看到我的评论,但我编辑了上面的回复以在变量替换周围添加双引号。双引号将强制未设置或空变量评估为空字符串。否则,如果 -eq 比较中的变量(如上述)为空或未设置,则会出现语法错误。
【解决方案2】:

看看this explanation of if

第一个==在字符串比较运算符部分,只能比较两个字符串。

第二个-eq 在最后一部分ARG1 OP ARG2(最后一个),它的文档说"ARG1" and "ARG2" are integers

【讨论】:

    【解决方案3】:

    -eq-lt-gt仅用于算术值比较(整数)。

    ==用于字符串比较。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-07
      • 2015-09-02
      • 2020-01-18
      • 1970-01-01
      • 2020-12-11
      • 2012-08-26
      • 2012-09-01
      • 1970-01-01
      相关资源
      最近更新 更多