When scripting is often written in operations, most people first think of using "-eq" for comparisons when using variables intermittently, but in fact if the variable value is null (NULL) for a special reason, bash shell converts null to 0 for "-eq" comparison, if you encounter this kind of confusion, you can change the integer comparison method to use string comparison (= =), which can be a good solution to the problem caused by the integer comparison. Why this article, precisely because the author of the online use of script operation process, so the bug occurred twice, but also brought some losses to the company, after careful analysis of the program log and script running logic, coupled with the following test process, only really found the location of the bug and solution. The following is the author of the thinking, for everyone to analyze the use.
[Email protected] ~]# echo $tables
[Email protected] ~]# echo $switch
[[Email protected] ~]# [[$tables-eq 0]] && Switch=off | | Switch=on
[Email protected] ~]# echo $switch
Off
[Email protected] ~]# unset switch
[Email protected] ~]# echo $switch
[[Email protected] ~]# [[$tables = = ^$] && Switch=off | | Switch=on
[Email protected] ~]# echo $switch
On
[Email protected] ~]# unset switch
[Email protected] ~]# echo $switch
[[Email protected] ~]# [[$tables = = [[: Space:]]] && Switch=off | | Switch=on
[Email protected] ~]# echo $switch
On
[Email protected] ~]# unset switch
[Email protected] ~]# echo $switch
[[Email protected] ~]# [[$tables = = "]] && Switch=off | | Switch=on
[Email protected] ~]# echo $switch
Off
[[Email protected]firewall ~]# unset switch
[Email protected] ~]# echo $switch
[[Email protected] ~]# [[0 = = "]] && Switch=off | | Switch=on
[Email protected] ~]# echo $switch
On
[Email protected] ~]# unset switch
[Email protected] ~]# echo $tables
[Email protected] ~]# echo $switch
[[Email protected] ~]# [[$tables = = 0]] && Switch=off | | Switch=on
[Email protected] ~]# echo $switch
On
[Email protected] ~]#
Bash shells can only do integer comparisons, floating-point numbers cannot use numeric comparisons, but they can be compensated for by using character comparisons, which are not error-free.
[[Email protected] ~]# [[11.11-eq 11.22]] && echo Wrong | | echo Right
-bash: [[: 11.11:syntax Error:invalid arithmetic operator (Error token is ". 11")
Right
[[Email protected] ~]# [[11.11 = 11.22]] && echo Wrong | | echo Right
Right
[[Email protected] ~]# [[11.11 = 11.12]] && echo Wrong | | echo Right
Right
[[Email protected] ~]# [[10.10 = 10.01]] && echo Wrong | | echo Right
Right
[Email protected] ~]#
Read this article carefully and follow the above code to test your friends in person, I believe you have a further understanding of bash shell weak type! Understand what weak-type language features are, and how bash shell numeric comparisons differ from character comparisons.
Bash Shell numeric comparison (-EQ) differs from character comparison (= =)