Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

The follwing code is for to compare two strings or variables. But, I cannot do it. I did a lot of googling, but no use. Here, output doesn't depend upon the changing of inputs. Can any one correct this code ??

#!/bin/sh  
echo "Enter your username1:"  
read username1  
echo "Enter your username2:"  
read useraname2  
if [ "$username1"=="$username2" ]  
then  
echo 'Same'  
else  
echo 'Different'  
fi
share|improve this question

2 Answers 2

Quick fix: add spaces around ==

The [ command does different things depending on how many arguments it receives. See http://www.gnu.org/software/bash/manual/bashref.html#index-test

When given 1 argument, the test command evaluates to true if the argument is a non-empty string. In your case that is guaranteed to be the case.

share|improve this answer
1  
Should also mention that == is not a standard operator for the [ command. In bash, == is treated the same as =, but for sh, only = is defined to work. –  geirha Aug 9 '13 at 17:44

This ran on my shell:

!/bin/sh

echo "Enter Username1:"

read username1

echo "Enter Username2:"

read username2

if [ "$username1" == "$username2" ]

then

echo "Same"

else

echo "different"

fi

share|improve this answer
    
So the basic problem is, as @geirha said, with your == operator use. Please try with = operator; the above script ran on my bash shell, sorry for the !/bin/sh. For sh, the same ran successfully with a single equal (=) sign for obvious reasons. –  Subhadeep Aug 18 '13 at 18:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.