I am trying to compare two strings in a Bash script and I am getting very strange results.
if [[ "010" < "01." ]]; then echo "Wrong"; else echo "OK"; fi
if [[ "010" < "01.0" ]]; then echo "Wrong"; else echo "OK"; fi
if [ "010" \< "01." ]; then echo "Wrong"; else echo "OK"; fi
if [ "010" \< "01.0" ]; then echo "Wrong"; else echo "OK"; fi
Reading the documentation, it seemed that [[ < ]]
and [ \< ]
should work the same, but they don't. It it seems that [[ < ]]
works wrong when the strings don't have the same length. Am I missing something?
The expected result is 4 x OK
. Tested on:
OK Wrong OK OK
)OK Wrong OK OK
)OK OK OK OK
)When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command. Use the == operator with the [[ command for pattern matching.
You can check the equality and inequality of two strings in bash by using if statement. “==” is used to check equality and “!= ” is used to check inequality of the strings. You can partially compare the values of two strings also in bash.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script.
Here is the documentation from help test
:
STRING1 > STRING2
True if STRING1 sorts after STRING2 lexicographically.
Taking your first if
statement as an example:
if [[ "010" < "01." ]]; then echo "Wrong"; else echo "OK"; fi
In Bash the string "01."
sorts lexicographically before the string "010"
(you can test in other tools like Microsoft Excel), so the comparison returns false. This is the case for all 4 of your comparisons.
Note that adding an additional 0
to the end of "01."
doesn't change the ordering versus "010"
, so you still get the same result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With