448

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
  • 13,327
  • 15
  • 60
  • 90

4 Answers4

591

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

Yu Hao
  • 115,525
  • 42
  • 225
  • 281
  • 1
    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
  • 90
    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
  • 13
    Is `-n` redundant with the default behavior of `if [ $2 ]` or are there some differences? – bbarker Jan 18 '19 at 18:32
70
-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.
34

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

knittl
  • 216,605
  • 51
  • 293
  • 340
26

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

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
mohit
  • 5,108
  • 3
  • 22
  • 37