bash shell数值比较(-eq)与字符比较(==)的区别
为什么会有此文章,正是因为笔者在线上使用脚本运维的过程中,因此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 ~]#