12

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.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • 1
    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. – aspyct Oct 21 '13 at 13:10
  • Yes, @Antoine_935, it will be problematic if the variable contains an space. It will become `if [ -z hello world ]` which `bash` won't be able to understand. – fedorqui Oct 21 '13 at 13:38

2 Answers2

20

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.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 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? – AndreaNobili Oct 21 '13 at 13:11
  • 2
    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...` – fedorqui Oct 21 '13 at 13:12
  • 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)? – AndreaNobili Oct 21 '13 at 13:19
  • Yes, exactly @AndreaNobili – fedorqui Oct 21 '13 at 13:20
5

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.

devnull
  • 118,548
  • 33
  • 236
  • 227