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.)

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
bpb101
  • 851
  • 1
  • 8
  • 17
  • is entering the words as hi hi okay – bpb101 Oct 26 '14 at 17:23
  • No, always use quote your variables so use: `if [ "$var1" = "$var2" ]; then` see my answer below on how to use `read`. – anubhava Oct 26 '14 at 17:43
  • See [How to debug a bash script](http://stackoverflow.com/questions/951336/how-to-debug-a-bash-script/951352#951352) 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). – Jonathan Leffler Oct 26 '14 at 19:56

2 Answers2

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
anubhava
  • 713,503
  • 59
  • 514
  • 593
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.

ROMANIA_engineer
  • 51,252
  • 26
  • 196
  • 186