整数比较 ron shell 时间 导致 erro opera 10.10 在线
运维中经常编写脚本时,如果遇到使用变量间歇取值并和整数进行比较时,大多数人第一时间会想到使用 "-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) 与字符比较 (==) 的区别
来源: http://www.bubuko.com/infodetail-2469051.html