Shell script variable not empty (-z option)

Shell

Shell Problem Overview


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

Shell Solutions


Solution 1 - Shell

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

Solution 2 - Shell

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

Solution 3 - Shell

I think this is the syntax you are looking for:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSreerajView Question on Stackoverflow
Solution 1 - ShellIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 2 - ShellWilliam PursellView Answer on Stackoverflow
Solution 3 - Shellvinod garagView Answer on Stackoverflow