Content #
可以使用test命令确定变量中是否为空。这只需要一个简单的条件表达式:
$ cat test6.sh
#!/bin/bash
# testing if a variable has content
#
my_variable="Full"
#
if test $my_variable
then
echo "The my_variable variable has content and returns a True."
echo "The my_variable variable content is: $my_variable"
else
echo "The my_variable variable doesn't have content,"
echo "and returns a False."
fi
$
$ ./test6.sh
The my_variable variable has content and returns a True.
The my_variable variable content is: Full
由于变量my_variable中包含内容(Full),因此当test命令测试条件时,返回的退出状态码为0。这使得then语句块中的语句得以执行。
如你所料,如果该变量中没有包含内容,就会出现相反的情况:
$ cat test6.sh
#!/bin/bash
# testing if a variable has content
#
my_variable=""
#
if test $my_variable
then
echo "The my_variable variable has content and returns a True."
echo "The my_variable variable content is: $my_variable"
else
echo "The my_variable variable doesn't have content,"
echo "and returns a False."
fi
$
$ ./test6.sh
The my_variable variable doesn't have content,
and returns a False.
From #
Linux命令行与shell脚本编程大全