-n和-z可以检查一个变量是否含有数据。
$ cat test10.sh
#!/bin/bash
# testing string length
val1=testing
val2=''
#
if [ -n $val1 ]
then
echo "The string '$val1' is not empty"
else
echo "The string '$val1' 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
$
$ ./test10.sh
The string 'testing' is not empty
The string '' is empty
The string '' is empty
$
这个例子创建了两个字符串变量。val1变量包含了一个字符串,val2变量包含的是一个空字符串。后续的比较如下:
if [ -n $val1 ]
判断val1变量是否长度非0,而它的长度正好非0,所以then部分被执行了。
if [ -z $var2 ]
判断val2变量是否长度为0,而它正好长度为0,所以then部分被执行了。
if [ -z $val3 ]
判断val3变量是否长度为0。这个变量并未在shell脚本中定义过,所以它的字符串长度仍然为0,尽管它未被定义过。