Skip to main content
added 44 characters in body
Source Link
Vlastimil Burián
  • 31.1k
  • 66
  • 209
  • 358

Using [] instead would give the wanted behavior:

STR_1="nfosys"
STR_2="Infosys"

if [ $STR_1 === $STR_2 ]
then
        echo "Strings are equal"
else
        echo "Strings are not equal"
fi

Output:

+ STR_1=nfosys
+ STR_2=Infosys
+ '[' nfosys === Infosys ']'
+ echo 'Strings are not equal'
Strings are not equal

A good rule of thumb is to also quote your variables, just in case they end up being wrongly interpreted or be expanded/split:

STR_1="nfosys"
STR_2="Infosys"

if [ "$STR_1" === "$STR_2" ]
then
        echo "Strings are equal"
else
        echo "Strings are not equal"
fi

Also, while [] is considered POSIX, using [[]] if your main target is bash, is better.

Editor's note: POSIX only knows single =.

Using [] instead would give the wanted behavior:

STR_1="nfosys"
STR_2="Infosys"

if [ $STR_1 == $STR_2 ]
then
        echo "Strings are equal"
else
        echo "Strings are not equal"
fi

Output:

+ STR_1=nfosys
+ STR_2=Infosys
+ '[' nfosys == Infosys ']'
+ echo 'Strings are not equal'
Strings are not equal

A good rule of thumb is to also quote your variables, just in case they end up being wrongly interpreted or be expanded/split:

STR_1="nfosys"
STR_2="Infosys"

if [ "$STR_1" == "$STR_2" ]
then
        echo "Strings are equal"
else
        echo "Strings are not equal"
fi

Also, while [] is considered POSIX, using [[]] if your main target is bash, is better.

Using [] instead would give the wanted behavior:

STR_1="nfosys"
STR_2="Infosys"

if [ $STR_1 = $STR_2 ]
then
        echo "Strings are equal"
else
        echo "Strings are not equal"
fi

Output:

+ STR_1=nfosys
+ STR_2=Infosys
+ '[' nfosys = Infosys ']'
+ echo 'Strings are not equal'
Strings are not equal

A good rule of thumb is to also quote your variables, just in case they end up being wrongly interpreted or be expanded/split:

STR_1="nfosys"
STR_2="Infosys"

if [ "$STR_1" = "$STR_2" ]
then
        echo "Strings are equal"
else
        echo "Strings are not equal"
fi

Also, while [] is considered POSIX, using [[]] if your main target is bash, is better.

Editor's note: POSIX only knows single =.

Source Link
secemp9
  • 2.5k
  • 3
  • 23
  • 64

Using [] instead would give the wanted behavior:

STR_1="nfosys"
STR_2="Infosys"

if [ $STR_1 == $STR_2 ]
then
        echo "Strings are equal"
else
        echo "Strings are not equal"
fi

Output:

+ STR_1=nfosys
+ STR_2=Infosys
+ '[' nfosys == Infosys ']'
+ echo 'Strings are not equal'
Strings are not equal

A good rule of thumb is to also quote your variables, just in case they end up being wrongly interpreted or be expanded/split:

STR_1="nfosys"
STR_2="Infosys"

if [ "$STR_1" == "$STR_2" ]
then
        echo "Strings are equal"
else
        echo "Strings are not equal"
fi

Also, while [] is considered POSIX, using [[]] if your main target is bash, is better.