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
  • 730,956
  • 141
  • 904
  • 1,278
bpb101
  • 971
  • 1
  • 9
  • 18
  • 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
  • 761,203
  • 64
  • 569
  • 643
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
  • 54,432
  • 29
  • 203
  • 199