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
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.
$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.
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.
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"
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
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 ]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With