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:
- CentOS release 6.4 (Final) - GNU Bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu) (
OK Wrong OK OK
) - Ubuntu 14.04.2 (Trusty Tahr) LTS - GNU Bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu) (
OK Wrong OK OK
) - openSUSE 13.1 (Bottle) (x86_64) - GNU Bash, version 4.2.53(1)-release (x86_64-suse-linux-gnu) (
OK OK OK OK
)
Here is the documentation from
help test
:Taking your first
if
statement as an example: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.