-n和-z可以检查变量中是否含有数据,其中:
-n 非空则返回True
-z 如果为空则返回True
例子:
[oracle@master test]$ cat testfile
#!/bin/bash
# Testing string length
val1=testing
val2=''
if [ -n $val1 ]
then
echo "The string '$val1' is not empty."
else
echo "The string '$val2' is empty."
fi
if [ -z val2 ]
then
echo "The string '$val2' is empty."
else
echo "The string '$val2' is not empty."
fi
if [ -z $val3 ]
then
echo "The string '$val3' is empty."
else
echo "The string '$val3' is not empty."
fi
[oracle@master test]$ sh testfile
The string 'testing' is not empty.
The string '' is not empty.
The string '' is empty.
总结:
如果不是很确定一个变量是否有值,最好使用-n或者-z检测一下,否则在运行程序时会得到意想不到的结果。