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
How to compare in shell script?
提问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
-gt
for 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 中进行比较
- Single-bracket syntax (
if [ ]
) - Double-parenthesis syntax (
if (( ))
)
- 单括号语法 (
if [ ]
) - 双括号语法 (
if (( ))
)
Using Single-bracket syntax
使用单括号语法
Operators :-
运营商:-
-eq
is equal to
-ne
is not equal to
-gt
is greater than
-ge
is greater than or equal to
-lt
is less than
-le
is 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