Shell等式运算符(=,==,-eq) [英] Shell equality operators (=, ==, -eq)

查看:286
本文介绍了Shell等式运算符(=,==,-eq)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下Shell脚本中===-eq之间的区别吗?

Can someone please explain the difference between =, == and -eq in shell scripting?

以下内容是否有区别?

[ $a = $b ]
[ $a == $b ]
[ $a -eq $b ]

仅当变量包含数字时才使用===吗?

Is it simply that = and == are only used when the variables contain numbers?

推荐答案

与此相反:===用于字符串比较,-eq用于数字比较. -eq-lt-le-gt-ge-ne属于同一家族,如果可以帮助您记住是哪个.

It's the other way around: = and == are for string comparisons, -eq is for numeric ones. -eq is in the same family as -lt, -le, -gt, -ge, and -ne, if that helps you remember which is which.

==是bash-ism.最好使用POSIX =.在bash中,这两个是等效的,而在普通情况下,sh =是唯一可以保证工作的.

== is a bash-ism, by the way. It's better to use the POSIX =. In bash the two are equivalent, and in plain sh = is the only one guaranteed to work.

$ a=foo
$ [ "$a" = foo ]; echo "$?"       # POSIX sh
0
$ [ "$a" == foo ]; echo "$?"      # bash specific
0
$ [ "$a" -eq foo ]; echo "$?"     # wrong
-bash: [: foo: integer expression expected
2

(附带说明:引用那些变量扩展!不要忽略上面的双引号.)

(Side note: Quote those variable expansions! Do not leave out the double quotes above.)

如果您正在编写#!/bin/bash脚本,那么我建议使用[[代替.双重形式具有更多功能,更自然的语法和更少的陷阱,可让您绊倒.对于$a,不再需要在双引号中加上双引号:

If you're writing a #!/bin/bash script then I recommend using [[ instead. The doubled form has more features, more natural syntax, and fewer gotchas that will trip you up. Double quotes are no longer required around $a, for one:

$ [[ $a == foo ]]; echo "$?"      # bash specific
0

另请参阅:

这篇关于Shell等式运算符(=,==,-eq)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆