525

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.

Noich
  • 14,631
  • 15
  • 62
  • 90

4 Answers4

693

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

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

slhck
  • 36,575
  • 28
  • 148
  • 201
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • 2
    I found another one excellent and detailed explanation - http://stackoverflow.com/questions/3601515/how-to-check-if-a-variable-is-set-in-bash – valentt May 11 '17 at 13:16
  • 110
    Also, `-n` is the opposite of `-z`. `if [ -n "${1}" ]` passes if the string is not null and not empty. – Ryan Mar 26 '18 at 23:48
  • 15
    Is `-n` redundant with the default behavior of `if [ $2 ]` or are there some differences? – bbarker Jan 18 '19 at 18:32
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.
38

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

knittl
  • 246,190
  • 53
  • 318
  • 364
33

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mohit
  • 5,696
  • 3
  • 24
  • 37
  • 3
    What if it is the string undefined (if that is a thing) or is a number? – Peter Mortensen Oct 05 '21 at 14:30
  • 1
    @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. – peterrus Sep 28 '22 at 14:14