Advertisement
Advertisement


Shell script variable not empty (-z option)


Question

How to make sure a variable is not empty with the -z option ?

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

It returns the error :

./test: line 2: [: !-z: unary operator expected
2013/09/19
1
57
9/19/2013 12:26:19 PM

Accepted Answer

Of course it does. After replacing the variable, it reads [ !-z ], which is not a valid [ command. Use double quotes, or [[.

if [ ! -z "$errorstatus" ]

if [[ ! -z $errorstatus ]]
91
7/6/2011 6:11:01 AM

Why would you use -z? To test if a string is non-empty, you typically use -n:

if test -n "$errorstatus"; then
  echo errorstatus is not empty
fi
2011/07/06

I think this is the syntax you are looking for:

if [ -z != $errorstatus ] 
then
commands
else
commands
fi
2012/09/23

Source: https://stackoverflow.com/questions/6592224
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]