简体   繁体   中英

Linux Shell if-statements about analyzing strings are equal

I am a beginner in Shell Programming.I am confused when I execute a program about if statement Code is as follows

echo -n "word 1:"
read word1
echo -n "word 2:"
read word2
if test "$word1"="$word2"
   then echo "Match"
fi

I found that regardless of whether I enter the same string,it always prints "Match"

That's what I want to ask,Thank you!

Add spaces around = :

if test "$word1" = "$word2"

Without them, you are using test on the expression "$word1"="$word2" to test if it is empty.

Silly, I know.

From man test :

-n STRING

the length of STRING is nonzero

STRING

equivalent to -n STRING

Just to be perfectly clear: First, $word1 and $word2 are replaced with the content of the variables, say hello and world to be original, so you get the string hello=world . So indeed, no matter what you will put in these variables, you will get a non-empty string (because of the = ) and so the test will always pass.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM