Bash -eq and ==, what's the diff?

浪尽此生 提交于 2021-02-05 06:37:32

问题


Why this works:

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

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

and this not?

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

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

What's the difference?? between == and -eq?

Thanks!


回答1:


-eq is an arithmetic test.

You are comparing strings.

From help test:

Other operators:

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

When you use [[ and use -eq as the operator, the shell attempts to evaluate the LHS and RHS. The following example would explain it:

$ 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



回答2:


Have a look at this explanation of if.

The first one == is in the section of string compare operators and it can only compare two strings.

The second one -eq is in the last section ARG1 OP ARG2(last one) and its documentation says "ARG1" and "ARG2" are integers.




回答3:


-eq, -lt, -gt is only used for arithmetic value comparison(integers).

== is used for string comparison.



来源:https://stackoverflow.com/questions/23086599/bash-eq-and-whats-the-diff

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!