变量没有定义或为空会导致shell test 表达式报错,为防止错误产生,[]中变量引用采用如下方式
if [ "X${name}" != "X" ]
then
do something;
在[ ] 中使用$a都会报错;
不能使用如下语句判断变量a是否定义,是否为空:
if [ $a == "" ];then
echo "a is null"
fi
if [ "" == $a ];then
echo "a is null"
echo "a is null"
fi
if [ X$a == X"" ];then
echo "a is null"
if [ "X${name}" != "X" ]
then
do something;
fi
判断一个变量是否定义,值是否为空同理:
------------------------------------------------------------------------------
无论是变量a没有定义,还是定义a=""在[ ] 中使用$a都会报错;
不能使用如下语句判断变量a是否定义,是否为空:
if [ $a == "" ];then
echo "a is null"
fi
if [ "" == $a ];then
echo "a is null"
fi
-----------------------------------------------------------------------------
判断变量a为空最好的方法是:[ -z string ] [ -n string ]
if [ -z $a ];then
echo "${LINENO} a is null"
fi
if [ -n $a ];then
echo "${LINENO} a is null"
fi
-----------------------也可以使用如下:
if [ X"" == X${a} ];thenecho "a is null"
fi
if [ X$a == X"" ];then
echo "a is null"
fi