Sreeraj
Sreeraj

Reputation: 723

Shell script variable not empty (-z option)

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

Upvotes: 72

Views: 175211

Answers (4)

Alexander
Alexander

Reputation: 51

if [ !-z $errorstatus ] just put a space between ! and -z, like this: if [ ! -z $errorstatus ]

Upvotes: 0

vinod garag
vinod garag

Reputation: 63

I think this is the syntax you are looking for:

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

Upvotes: 3

William Pursell
William Pursell

Reputation: 212248

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

Upvotes: 32

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798646

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 ]]

Upvotes: 114

Related Questions