Download your favorite Linux distribution at LQ ISO.
Go Back > Forums > Linux Forums > Linux - Newbie
User Name
Linux - Newbie This Linux forum is for members that are new to Linux.
Just starting out and have a question? If it is not in the man pages or the how-to's this is the place!


  Search this Thread
Old 06-28-2012, 06:02 AM   #1
LQ Newbie
Registered: Apr 2007
Posts: 6

Rep: Reputation: 0
linux shell script comparing strings containing spaces

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"
echo "strings are different"

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?
Old 06-28-2012, 07:46 AM   #2
LQ Guru
Registered: May 2005
Location: Atlanta Georgia USA
Distribution: Redhat (RHEL), CentOS, Fedora, CoreOS, Debian, FreeBSD, HP-UX, Solaris, SCO
Posts: 6,807
Blog Entries: 14

Rep: Reputation: 1069Reputation: 1069Reputation: 1069Reputation: 1069Reputation: 1069Reputation: 1069Reputation: 1069Reputation: 1069
Put quotes around the variables in your test:

if [ "$str1" == "$str2" ]
echo "strings are equal"
echo "strings are different"
NB: I added the "then" above as it wasn't in your original post but is necessary.
1 members found this post helpful.
Old 06-28-2012, 10:36 PM   #3
LQ Newbie
Registered: Apr 2007
Posts: 6

Original Poster
Rep: Reputation: 0
Thumbs up

Thanks Boss!!!
It worked..


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Comparing strings in linux raviraj2018 Linux - Software 3 07-30-2009 03:04 AM
comparing 2 strings in shell script dhanabalanb Programming 3 08-01-2007 01:17 PM
Shell script for comparing certain lines in two files mou5e Linux - Newbie 9 06-06-2007 01:40 PM

All times are GMT -5. The time now is 06:33 PM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration