Argument isn't passed (bash)

I'm working with shell scripts.

I'm in the test section, where if an argument is passed:

The expression is true if, and only if, the argument is not null

And here I have implemented the following code:

[ -z $num ]; echo $?;

Your exit:

0

Why?

Upvotes: 0

Views: 366

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74595

Firstly, [-z should be [ -z, otherwise you would be getting an error like [-z: command not found. I guess that was just a typo in your question.

It sounds like you're quoting the wrong part of the manual, which would apply to tests like this:

[ string ]    # which is equivalent to
[ -n string ]

Either of which would return success (a 0) for a non-empty string.

With -z, you're checking that the length of the string is 0.

However, as always, be careful with unquoted variables, since:

[ -z $num ]
# expands to
[ -z ]
# which is interpreted in the same way as
[ string ]

i.e. your test becomes "is -z a non-empty string?", to which the answer is yes, so the test returns 0. If you use quotes around "$num" then the test does what you would expect.

Upvotes: 4

Related Questions