1
echo "please enter 2 word"
read var1 var2
if [ "$var 1" = "$var2" ]; then
    echo "These string are the same"
else
    echo "the strings are different"
fi;

The if statement is coming out as false and it's printing the else echo. I looked on various sites and they say this is the format it should be. Am I making some syntax errors?

Solution

 if [ "$var1" = "$var2" ]; then

(No space between $var and 1 in the condition.)

3
  • is entering the words as hi hi okay Commented Oct 26, 2014 at 17:23
  • No, always use quote your variables so use: if [ "$var1" = "$var2" ]; then see my answer below on how to use read. Commented Oct 26, 2014 at 17:43
  • See How to debug a bash script for some information on debugging scripts — the output would have shown you some of your problems (" 1" clearly would be different from one of the words you typed, for example). Commented Oct 26, 2014 at 19:56

2 Answers 2

2

Problem is this line:

if [ "$var 1" = "$var2" ]; then
          ^---< extra space here <---

Replace this line with:

if [ "$var1" = "$var2" ]; then

EDIT:: To make sure you read both values in two separate variable use IFS like this:

IFS=' ' && read var1 var2
Sign up to request clarification or add additional context in comments.

4 Comments

That depends on what values you're entering after read. If you enter abc abc then if block will print These string are the same
Add echo for strings + for their length after the read line and be sure that your strings are the same.
Print your variables as echo "|var1| |$var2|"
Also see my EDIT section.
1
echo "please enter 2 word"
read var1 
read var2
if [ "$var1" = "$var2" ]; then
    echo "These string are the same"
else
    echo "the strings are different"
fi;

You have to read variables 1 by 1, not in same line.

2 Comments

This is one option. The other is to simply enter words separated by a space.
i dont think it makes a differences but either way its still saying different

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.