Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 666
Mr Shoubs Avatar asked Nov 25 '10 13:11

Mr Shoubs


People also ask

How do you check if two strings are equal in shell script?

Details. Use == operator with bash if statement to check if two strings are equal. You can also use != to check if two string are not equal.

How do I compare two string variables in Unix?

You can check the equality and inequality of two strings in bash by using if statement. “==” is used to check equality and “!= ” is used to check inequality of the strings.

What is the difference between the == and comparison operator when used in bash?

In shell scripting, = and == are for string comparisons and -eq is for numeric ones. So, when comparing the strings, use = or == (depending on which shell you are using, sh or bash ), while to check for equality between integers, use -eq comparison operator.


1 Answers

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" ]] 
like image 195
moinudin Avatar answered Sep 19 '22 10:09

moinudin