Mr Shoubs Mr Shoubs - 5 months ago 15
Linux Question

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

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

For string comparison, use:

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

For the a contains b, use:

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