How do I compare two string variables in an 'if' statement in Bash? [duplicate] How do I compare two string variables in an 'if' statement in Bash? [duplicate] bash bash

How do I compare two string variables in an 'if' statement in Bash? [duplicate]


For string equality comparison, use:

if [[ "$s1" == "$s2" ]]

For string does NOT equal comparison, use:

if [[ "$s1" != "$s2" ]]

For the a contains b, use:

if [[ $s1 == *"$s2"* ]]

(and make sure to add spaces between the symbols):

Bad:

if [["$s1" == "$s2"]]

Good:

if [[ "$s1" == "$s2" ]]


You need spaces:

if [ "$s1" == "$s2" ]


You should be careful to leave a space between the sign of '[' and double quotes where the variable contains this:

if [ "$s1" == "$s2" ]; then#   ^     ^  ^     ^   echo matchfi

The ^s show the blank spaces you need to leave.