Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script variable not empty (-z option)

Tags:

shell

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 
like image 244
Sreeraj Avatar asked Jul 06 '11 06:07

Sreeraj


People also ask

What is if [- Z in bash?

In both cases, the -z flag is a parameter to the bash's "test" built-in (a built-in is a command that is built-into the shell, it is not an external command). The -z flag causes test to check whether a string is empty. Returns true if the string is empty, false if it contains something.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script.

What does Z do in shell script?

The Z shell (Zsh) is a Unix shell that can be used as an interactive login shell and as a command interpreter for shell scripting. Zsh is an extended Bourne shell with many improvements, including some features of Bash, ksh, and tcsh.

How do you check if a variable is not empty in a shell?

To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"


2 Answers

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 
like image 41
William Pursell Avatar answered Sep 18 '22 23:09

William Pursell


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 ]] 
like image 153
Ignacio Vazquez-Abrams Avatar answered Sep 21 '22 23:09

Ignacio Vazquez-Abrams