首页 Linux 正文
31

Bash脚本中的-eq, =和==

  • yiqingpeng
  • 2022-04-11
  • 0
  •  
-eq 是用来比较数值的,如果是字符串,会转化为数值,所以 [ 'yes' -eq 0 ] 或 [[ 'yes' -eq 0 ]] 测试结果都为TRUE.
= 单等号 和 == 双等号都是用来比较字符串的,它们放在[ ... ]和[[ ... ]]中表现是不一样的,主要体现在有没有对操作数加双引号括起来会不一样的处理。具体看这个post: 
[ $a == $b ], specifically used unquoted 
variable substitution (as of the October 2017 edit). 
For [...] that is safe for string equality.

But if you are going to enumerate alternatives like [[...]], 
you must inform also that the right-hand-side must be quoted. 
If not quoted, it is a pattern match! 
(From the Bash man page: "Any part of the pattern may be quoted to 
force it to be matched as a string.").

Here in Bash, the two statements yielding "yes" are pattern matching, 
other three are string equality:

> rht="A*"
> lft="AB"
> [ $lft = $rht ] && echo yes
#不会执行echo yes

> [ $lft == $rht ] && echo yes
#不会执行echo yes

> [[ $lft = $rht ]] && echo yes
#输出 yes

> [[ $lft == $rht ]] && echo yes
#输出 yes

> [[ $lft == "$rht" ]] && echo yes
#不会执行echo yes

正在加载评论...