What means the -z value in an if expression on a Linux script?

15,556

Solution 1

From man test:

   -z STRING
          the length of STRING is zero

So the condition:

if [ -z $1 ]; then

means "if the variable $1 is empty". Where $1 is probably the first parameter of the script: if you execute it like ./script <parameter1> <parameter2>, then $1=parameter1, $2=parameter2 and so forth.

Solution 2

help test tells:

String operators:

  -z STRING      True if string is empty.

In your example, the script would print Usage: createpkg.sh <rev package> and exit if an argument was not supplied.

Share:
15,556

Related videos on Youtube

AndreaNobili
Author by

AndreaNobili

Updated on September 15, 2022

Comments

  • AndreaNobili
    AndreaNobili over 1 year

    In this script I found this if expression:

    if [ -z $1 ]; then
        echo "Usage: createpkg.sh <rev package>"
        exit
    else
        CURRENT_VERSION=$1
    fi
    

    My problem is that I can't find what exactly means this -z value.

    From the content of the echo I can deduct that (maybe) $1 variable represents the sotware version. and that (maybe) -z is a void value. So if I execute the script without passing to it the version of the software that I would packing it print me the correct procedure to execute the script.

    But I am not sure about the real meaning of the -z value.

    • aspyct
      aspyct over 10 years
      As a side note, you should probably enclose your variable in quotes. if [ -z "$1" ];. I don't remember the exact reason (someone ?) but not doing so can result in unwanted behavior in some cases.
  • devnull
    devnull over 10 years
    It's a shell built-in. Type type test to verify!
  • AndreaNobili
    AndreaNobili over 10 years
    Yes, also I think that $1 is the firs parameter of my script but...where are definied the script parameter? how can I associate a parameter to a variable?
  • fedorqui
    fedorqui over 10 years
    You have to check how the script is executed. If its name is "myscript.sh" then somewhere you will find a call ./myscript.sh param1 param2... or /bin/sh /path/to/myscript.sh param1 param2...
  • AndreaNobili
    AndreaNobili over 10 years
    I think that the script is executed in the shell with this command: createpkg.sh 2 (that create the package of the 2 version of the sofware) So the $1 variable is automatically bounded to the first parameter value (in this case: 2)?
  • fedorqui
    fedorqui over 10 years
    Yes, exactly @AndreaNobili