Bash string comparison examples

Operator =

    # if [ "abc" = "abc" ] ; then echo true; fi
    true
    # if [ abc = abc ] ; then echo true; fi
    true
    # a="abc"
    # b="abc"
    # if [ $a = $b ] ; then echo true; fi
    true
    # if [ "$a" = "$b" ] ; then echo true; fi
    true
    # if [ '$a' = '$b' ] ; then echo true; else echo false fi
    false
    # if [ '$a' = "$b" ] ; then echo true; else echo false fi
    false

Operator ==

This is a synonym for =
Unless == comparison operator used. Before start examples, here is the explaination.
    [[ $a == z* ]]   # True if $a starts with an "z" (pattern matching).

    [[ $a == "z*" ]] # True if $a is equal to z* (literal matching).

    [ $a == z* ]     # File globbing and word splitting take place.

    [ "$a" == "z*" ] # True if $a is equal to z* (literal matching).
Examples
# if [[ $a == *b* ]] ; then echo true; fi
true
# if [[ "$a" == *b* ]] ; then echo true; fi
true
# if [[ "$a" == "*b*" ]] ; then echo true; else echo false fi
false

$if [ $a == *b* ] ; then echo true; fi
bash: [: too many arguments
$touch abc # create an empty file abc, then  run test again

$if [ $a == *b* ] ; then echo true; fi
bash: [: too many arguments


# It will only show true if there is only one file name matches.
$if [ $a == ab* ] ; then echo true; fi
true
Similar to

$if ls ab* ; then echo true ;fi
abc
true

Operator !=

is not is not equal to
if [ "$a" != "$b" ]
This operator uses pattern matching within a [[ ... ]] construct.
Example:
$if [ $a != $b ] ; then echo true; fi
bash: [: abc: unary operator expected

$if [[ $a != $b ]] ; then echo true; else echo false; fi
false

$if [[ $a != c* ]] ; then echo true; else echo false; fi
true

Operator =~

Uses pattern matching within a [[...]] construct.
$if [[ $a =~ c* ]] ; then echo true; else echo false; fi
true

Operator > and <

$if [[ $a > b ]] ; then echo true; fi
$if [[ $a > a ]] ; then echo true; fi
true
$if [[ $a < z ]] ; then echo true; fi
true
$if [[ $a < a ]] ; then echo true; fi
You can get the same result by using single bracket.

if [[ "$a" < "$b" ]]

if [ "$a" \< "$b" ]

Note that the "<" needs to be escaped within a [ ] construct.

Operator -z

string is null, that is, has zero length

Operator -n

string is not null.

$if [ -n "$a" ]; then echo no null; fi
no zero
$if [ -n $a ]; then echo no null; fi
no zero
$if [ -n abc ]; then echo no null; fi
no zero
$if [ -n "abc" ]; then echo no null; fi
no zero

   Note: The -n test requires that the string be quoted within the test brackets. Uing an unquoted string with !-z, or even just the unquoted string alone with test brackets normally works, however, this is an unsafe practice. Always quote a tested string