比较shell脚本中的字符串不能按预期工作

时间:2014-10-26 17:18:05

标签: shell

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;

if语句将显示为false并且正在打印else echo。我查看了各种网站,他们说这是应该的格式。我是否犯了一些语法错误?

解决方案

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

(条件中$var1之间没有空格。)

2 个答案:

答案 0 :(得分:2)

问题在于这一行:

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

将此行替换为:

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

编辑:: 为了确保您在两个单独的变量中读取这两个值,请使用IFS,如下所示:

IFS=' ' && read var1 var2

答案 1 :(得分: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;

你必须逐个读取变量,而不是在同一行。