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

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

问题描述

===-eq 在 shell 脚本中有什么区别?

What is 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 主义.最好使用 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天全站免登陆