一个shell脚本:
#!/bin/sh
#ifelif
echo "Enter your name: "
read NAME
if [ $NAME = "" ] || [ -z $NAME ]
then
echo "You don't enter your name."
elif [ $NAME = "root" ]
then
echo "Hello root."
elif [ $NAME = "Tom" ]
then
echo "Hello Tom."
else
echo "You aren't root or Tom in $NAME."
fi
在我测试空串的时候,出现问题,报错为./ifelif: line 5: [: =: unary operator expected,后来发现问题是出现在双引号上。
if [ $NAME = "" ] 在进行空串处理时,实际为if [ = "" ] ,这在处理时当然会报操作符异常,因此我们需要在变量上加上双引号即if [ "$NAME" = "" ],这样你在测试空串时,为if [ "" = "" ],shell脚本才会通过。 虽然shell中有没有双引号很多情况下是一致的,但是为了保证正确性,在比较字符串时加上还是一种好的习惯。