DeaIss
DeaIss

Reputation: 2585

Unix bash scripting and using the test -z script

So I wrote a script called MYSCRIPT with this code:

if test -z $1 ; then
  echo "rm: missing operand"
  echo "'try rm --help'" for more information.
fi

From my understanding it means: "If the $1 parameter does not exist, then echo: "rm: missing operand".

Yet if type "sh MYSCRIPT -i" then it still echoes this. Surely the $1 parameter is now equal to something (it is -i) so it should run?

Upvotes: 0

Views: 609

Answers (1)

fedorqui
fedorqui

Reputation: 290015

This is one way but maybe not the best way to check if the argument given is empty.

I suggest you to use something like this, that counts the number of parameters given:

#!/bin/bash

[ $# -eq 0 ] && echo "no arguments given" && exit

echo "$1 is the input"

Test

$ ./test
no arguments given
$ ./test a
a is the input

Upvotes: 1

Related Questions