bash 用于比较的 Shell 脚本算术运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13675531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:55:09  来源:igfitidea点击:

Shell Scripting Arithmetic Operators for Comparison

bashshellscriptingcomparisonoperators

提问by Sugihara

I am trying to learn shell scripting and following the tutorials on tutorialspoint when I came across this problem with arithmetic comparison.

当我在算术比较中遇到这个问题时,我正在尝试学习 shell 脚本并遵循 tutorialspoint 上的教程。

$VAL1=10
$VAL2=20
$VAL3=10

if [ $VAL1 == $VAL2 ]
then
    echo "equal"
else
    echo "not equal"
fi

but I got a [: ==: unexpected operatorI am not sure why the comparison operator did not work. I know I can also use rational operators, but I want to know why '==' is not defined.

但我得到了一个[: ==: unexpected operator我不知道为什么比较运算符不起作用。我知道我也可以使用有理运算符,但我想知道为什么没有定义“==”。

回答by sampson-chen

You want to change it to:

您想将其更改为:

VAL1=10
VAL2=20
VAL3=10

if [ "$VAL1" -eq "$VAL2" ]
then
    echo "equal"
else
    echo "not equal"
fi

Explanations:

说明:

  • Don't add the $for the lvalue (variable being assigned) in an assignment.
  • Always wrap your variables with double-quotes in tests. The [: ==: unexpected operatorerror you got is because, since VAL1/ VAL2were not assigned properly earlier, ksh expansion of your test actually ends up resolving to this: if [ == ]- (but you see that it's actually not a problem about ==being undefined)
  • Use the following for numeric comparisons instead of the ==notation:
    • -eq(==)
    • -ne(!=)
    • -gt(>)
    • -ge(>=)
    • -lt(<)
    • -le(<=)
  • 不要$在赋值中为左值(被赋值的变量)添加。
  • 在测试中始终用双引号将变量括起来。[: ==: unexpected operator你得到的错误是因为VAL1/VAL2之前没有正确分配,你的测试的 ksh 扩展实际上最终解决了这个if [ == ]问题==:-(但你看到它实际上不是未定义的问题)
  • 使用以下进行数字比较而不是==表示法:
    • -eq(==)
    • -ne(!=)
    • -gt(>)
    • -ge(>=)
    • -lt(<)
    • -le(<=)