Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash string comparison

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)
like image 796
Marin Avatar asked Jun 15 '15 08:06

Marin


People also ask

How do I compare two string variables in bash?

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.

How do I compare characters in bash?

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.

Can you use == to compare strings?

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.

What does [- Z $1 mean in bash?

$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.


1 Answers

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.

like image 108
Tim Biegeleisen Avatar answered Oct 05 '22 22:10

Tim Biegeleisen