Shell脚本变量不为空(-z选项)

时间:2011-07-06 06:09:02

标签: shell

如何使用-z选项确保变量为空?

errorstatus="notnull"
if [ !-z $errorstatus ]
then
   echo "string is not null"
fi

它返回错误:

./test: line 2: [: !-z: unary operator expected

3 个答案:

答案 0 :(得分:81)

当然可以。替换变量后,它会读取[ !-z ],这不是有效的[命令。使用双引号或[[

if [ ! -z "$errorstatus" ]

if [[ ! -z $errorstatus ]]

答案 1 :(得分:25)

为什么要使用-z?要测试字符串是否为非空,通常使用-n:

if test -n "$errorstatus"; then
  echo errorstatus is not empty
fi

答案 2 :(得分:3)

我认为这是您正在寻找的语法:

if [ -z != $errorstatus ] 
then
commands
else
commands
fi