运算符 说明
= 检测两个字符串是否相等,相等返回 true。
!= 检测两个字符串是否不相等,不相等返回 true。
-z 检测字符串长度是否为0,为0返回 true。
-n 检测字符串长度是否不为0,不为0返回 true。
检测字符串是否不为空,不为空返回 true。
示例:
#!/bin/sh
a="abc"
b="def"
c=""
if [ $a = $b ]
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi
if [ $a != $b ]
then
echo "a is not equal to b"
else
echo "a is equal to b"
fi
if [ -z $a ]
then
echo "string a length is zero"
else
echo "string a length is not zero"
fi
if [ -z $c ]
then
echo "string c length is zero"
else
echo "string c length is not zero"
fi
if [ -n $a ]
then
echo "string a length is not zero"
else
echo "string a length is zero"
fi
if [ $a ]
then
echo "string a is not empty"
else
echo "string a is empty"
fi
if [ $c ]
then
echo "string c is not empty"
else
echo "string c is empty"
fi
if [ $d ]
then
echo "string d is not empty"
else
echo "string d is empty"
fi
if [ -z $d ]
then
echo "string d length is zero"
else
echo "string d length is not zero"
fi
结果:
a is not equal to b
a is not equal to b
string a length is not zero
string c length is zero
string a length is not zero
string a is not empty
string c is empty
string d is empty
string d length is zero