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

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


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



[root@lovefirewall ~]# echo $tablesshell

[root@lovefirewall ~]# echo $switchbash

[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 $switchide

[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 $switchspa

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

[root@lovefirewall ~]# echo $switchtoken

[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 ~]# it



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

相关文章
相关标签/搜索