What does -z mean in Bash? [duplicate]
Asked Answered
H

4

546

I'm looking at the following code:

if [ -z $2 ]; then
        echo "usage: ...

(The 3 dots are irrelevant usage details.)
Maybe I'm googling it wrong, but I couldn't find an explanation for the -z option.

Huberthuberto answered 7/8, 2013 at 7:0 Comment(2)
#6666041Movie
#229044Movie
J
718

-z string: True if the string is null (an empty string)

See https://www.gnu.org/software/bash/manual/bash.html#Bash-Conditional-Expressions

Janiuszck answered 7/8, 2013 at 7:4 Comment(3)
I found another one excellent and detailed explanation - #3602015Complacent
Also, -n is the opposite of -z. if [ -n "${1}" ] passes if the string is not null and not empty.Malcommalcontent
Is -n redundant with the default behavior of if [ $2 ] or are there some differences?Wallace
B
75
-z

string is null, that is, has zero length

String=''   # Zero-length ("null") string variable.

if [ -z "$String" ]
then
  echo "\$String is null."
else
  echo "\$String is NOT null."
fi     # $String is null.
Borodin answered 7/8, 2013 at 7:3 Comment(0)
C
39

test -z returns true if the parameter is empty (see man sh or man test).

Changchangaris answered 7/8, 2013 at 7:2 Comment(0)
M
36

The expression -z string is true if the length of string is zero.

Maratha answered 7/8, 2013 at 7:2 Comment(2)
What if it is the string undefined (if that is a thing) or is a number?Supervisory
@PeterMortensen if you use if [[ -z "${YOUR_ENV_VAR}" ]] it will get interpolated to if [[ -z "" ]] at runtime when that env var is empty, thus resulting in a logical true, which is what you want.Mellar

© 2022 - 2024 — McMap. All rights reserved.