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

Mr Shoubs picture Mr Shoubs · Nov 25, 2010 · Viewed 1.1M times · Source

I'm trying to get an if statement to work in Bash (using Ubuntu):

#!/bin/bash

s1="hi"
s2="hi"

if ["$s1" == "$s2"]
then
  echo match
fi

I've tried various forms of the if statement, using [["$s1" == "$s2"]], with and without quotes, using =, == and -eq, but I still get the following error:

[hi: command not found

I've looked at various sites and tutorials and copied those, but it doesn't work - what am I doing wrong?

Eventually, I want to say if $s1 contains $s2, so how can I do that?

I did just work out the spaces bit... :/ How do I say contains?

I tried

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

but it didn't work.

Answer

moinudin picture moinudin · Nov 25, 2010

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" ]]