LinuxQuestions.org
Welcome to the most active Linux Forum on the web.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Linux Forums > Linux - Newbie
User Name
Password
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!

Notices


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

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

Rep: Reputation: 1669Reputation: 1669Reputation: 1669Reputation: 1669Reputation: 1669Reputation: 1669Reputation: 1669Reputation: 1669Reputation: 1669Reputation: 1669Reputation: 1669
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.
 
1 members found this post helpful.
Old 06-28-2012, 10:36 PM   #3
tinaelizabeth84
LQ Newbie
 
Registered: Apr 2007
Posts: 6

Original Poster
Rep: Reputation: 0
Thumbs up

Thanks Boss!!!
It worked..
 
  


Reply



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

LinuxQuestions.org > Forums > Linux Forums > Linux - Newbie

All times are GMT -5. The time now is 04:08 PM.

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