shell脚本,if判断语句报错[: too many arguments
我遇到过两种情况:
1、第一中情况就是网上大家说的,字符串变量中可能存在空格,shell解析时将其认为是多个参数,再进行判断时,无法知道该获取哪个值,例如:
脚本ee.sh:
strings1="hello world"
strings2="hello world"if [ $strings1 = $strings2 ]
then
echo "strings1 is same as strings2"
else
echo "strings1 is different from strings2"
fi
执行结果中报错:
ee.sh: line 3: [: too many arguments
strings1 is different from strings2
并自动执行了else分支中的语句。
而下面这段语句就不会这样:
脚本ee.sh:
strings1="hello world"
strings2="hello world"
if [ "$strings1" = "$strings2" ]
then
echo "strings1 is same as strings2"
else
echo "strings1 is different from strings2"
fi
执行结果:strings1 is same as strings2
2、第二种是我自己初步接触shell脚本,很多语法规则不太熟悉时遇到的,我将其记为——多重判断:
还是以上面的例子,将第二段稍微改一下:
脚本ee.sh:
strings1="hello world"
strings2="hello world"
if [ "$strings1" = "$strings2" -eq 1 ]
then
echo "strings1 is same as strings2"
else
echo "strings1 is different from strings2"
fi
执行结果:
ee.sh: line 3: [: too many arguments
strings1 is different from strings2
这里是按照常规的思路来写的,“ "$strings1" = "$strings2"先判断两个字符串是否相等,如果相等这个结果就是true,而true在一般语言中通常可以等价于1,因此又将这个结果跟1进行比较”,其实在这个逻辑中,我忽略了"$strings1" = "$strings2"本身就是个判断条件,执行结果就是true或false,而不需要再对这个结果判断它是否是1.