码迷,mamicode.com
首页 > 系统相关 > 详细

bash shell数值比较(-eq)与字符比较(==)的区别

时间:2018-01-21 01:11:08      阅读:2033      评论:0      收藏:0      [点我收藏+]

标签:operator   ace   error   带来   roo   公司   运维   运行   ror   

运维中经常编写脚本时,如果遇到使用变量间歇取值并和整数进行比较时,大多数人第一时间会想到使用"-eq"进行比较,但事实中如果因特殊原因导致变量取值为空(null)时,bash shell会把null转换为0进行"-eq"比较,如果遇到此种困惑,可以把整数比较方法改为使用字符串比较(==),这样就可以很好的解决整数比较带来的这种bug。

为什么会有此文章,正是因为笔者在线上使用脚本运维的过程中,因此bug出现过两次失手,也给公司带来了带来了一些损失,经过仔细分析程序日志和脚本运行逻辑,加上如下测试过程,才真正找到了bug的所在以及解决办法。以下是笔者推敲思路,供大家分析之用。



[root@lovefirewall ~]# echo $tables

[root@lovefirewall ~]# echo $switch

[root@lovefirewall ~]# [[ $tables -eq 0 ]] && switch=off || switch=on
[root@lovefirewall ~]# echo $switch
off
[root@lovefirewall ~]# unset switch
[root@lovefirewall ~]# echo $switch

[root@lovefirewall ~]# [[ $tables == ^$ ]] && switch=off || switch=on
[root@lovefirewall ~]# echo $switch
on
[root@lovefirewall ~]# unset switch
[root@lovefirewall ~]# echo $switch

[root@lovefirewall ~]# [[ $tables == [[:space:]] ]] && switch=off || switch=on
[root@lovefirewall ~]# echo $switch
on
[root@lovefirewall ~]# unset switch
[root@lovefirewall ~]# echo $switch

[root@lovefirewall ~]# [[ $tables == "" ]] && switch=off || switch=on
[root@lovefirewall ~]# echo $switch
off
[root@lovefirewall ~]# unset switch
[root@lovefirewall ~]# echo $switch

[root@lovefirewall ~]# [[ 0 == "" ]] && switch=off || switch=on
[root@lovefirewall ~]# echo $switch
on
[root@lovefirewall ~]# unset switch
[root@lovefirewall ~]# echo $tables

[root@lovefirewall ~]# echo $switch

[root@lovefirewall ~]# [[ $tables == 0 ]] && switch=off || switch=on
[root@lovefirewall ~]# echo $switch
on
[root@lovefirewall ~]#


bash shell只能做整数比较,浮点数无法使用数值比较,但好在可以使用字符比较进行弥补,字符的比较是没有误差的

[root@lovefirewall ~]# [[ 11.11 -eq 11.22 ]] && echo wrong || echo right
-bash: [[: 11.11: syntax error: invalid arithmetic operator (error token is ".11")
right
[root@lovefirewall ~]# [[ 11.11 == 11.22 ]] && echo wrong || echo right
right
[root@lovefirewall ~]# [[ 11.11 == 11.12 ]] && echo wrong || echo right
right
[root@lovefirewall ~]# [[ 10.10 == 10.01 ]] && echo wrong || echo right
right
[root@lovefirewall ~]#



仔细阅读本文内容并按上述代码亲自测试一轮的朋友,相信你对bash shell弱类型又有了更进一步的认识了吧!理解了什么是弱类型语言特性,以及bash shell数值比较与字符比较的区别。

bash shell数值比较(-eq)与字符比较(==)的区别

标签:operator   ace   error   带来   roo   公司   运维   运行   ror   

原文地址:http://blog.51cto.com/183530300/2063291

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!