LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   linux shell script comparing strings containing spaces (https://www.linuxquestions.org/questions/linux-newbie-8/linux-shell-script-comparing-strings-containing-spaces-4175413813/)

tinaelizabeth84 06-28-2012 06:02 AM

linux shell script comparing strings containing spaces
 
Hi,
am trying to write a shell script.
I have two strings say str1 and str2
I need to check if str1 and str2 are equal.
I used the following piece of code

if [ $str1 == $str2 ]
echo "strings are equal"
else
echo "strings are different"
fi

if i run this script and give str1 as hello ,it works fine.but if i give something like hello world it shows an error saying

: too many arguments

I tried giving str 1 as "a b" and got the same error.

So I guess its the space in between characters that gives the error.
Can any1 help me out?

MensaWater 06-28-2012 07:46 AM

Put quotes around the variables in your test:

Code:

if [ "$str1" == "$str2" ]
then
echo "strings are equal"
else
echo "strings are different"
fi

NB: I added the "then" above as it wasn't in your original post but is necessary.

tinaelizabeth84 06-28-2012 10:36 PM

Thanks Boss!!!
It worked..


All times are GMT -5. The time now is 07:01 PM.