Linux 如何在shell脚本中进行比较?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5343420/
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-08-05 03:18:04  来源:igfitidea点击:

How to compare in shell script?

linuxbashshellcommand-line

提问by Tom Brito

How to compare in shell script?

如何在shell脚本中进行比较?

Or, why the following script prints nothing?

或者,为什么以下脚本不打印任何内容?

x=1
if[ $x = 1 ] then echo "ok" else echo "no" fi

采纳答案by William Durand

With numbers, use -eq, -ne, ... for equals, not equals, ...

对于数字,使用-eq, -ne, ... 表示等于,不等于,...

x=1
if [ $x -eq 1 ]
then 
  echo "ok" 
else 
  echo "no" 
fi

And for others, use ==not =.

对于其他人,请使用==not =

回答by Aif

It depends on the language. With bash, you can use ==operator. Otherwize you may use -eq-lt-gtfor equals, lowerthan, greaterthan.

这取决于语言。使用 bash,您可以使用==运算符。否则,您可以使用-eq-lt-gt等于、低于、大于。

$ x=1
$ if [ "$x" == "2" ]; then echo "yes"; else echo "no"; fi
no

Edit: added spaces arround ==and tested with 2.

编辑:在周围添加空格==并使用 2 进行测试。

回答by user unknown

Short solution with shortcut AND and OR:

带有快捷方式 AND 和 OR 的简短解决方案:

x=1
(( $x == 1 )) && echo "ok" || echo "no"

回答by anoopknr

You could compare in shell in two methods

您可以通过两种方法在 shell 中进行比较

  1. Single-bracket syntax ( if [ ])
  2. Double-parenthesis syntax ( if (( )))
  1. 单括号语法 ( if [ ])
  2. 双括号语法 ( if (( )))


Using Single-bracket syntax

使用单括号语法

Operators :-

运营商:-

-eqis equal to

-neis not equal to

-gtis greater than

-geis greater than or equal to

-ltis less than

-leis less than or equal to

-eq等于

-ne不等于

-gt大于

-ge大于或等于

-lt小于

-le小于或等于

In Your case :-

在你的情况下:-

x=1
if [ $x -eq 1 ]
then 
  echo "ok" 
else 
  echo "no" 
fi

Double-parenthesis syntax

双括号语法

Double-parentheses construct is also a mechanism for allowing C-style manipulation of variables in Bash, for example, (( var++ )).

双括号构造也是一种允许C在 Bash 中对变量进行样式操作的机制,例如,(( var++ )).

In your case :-

在你的情况下:-

x=1
if (( $x == 1 )) # C like statements 
then
    echo "ok"
else
    echo "no"
fi