Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A case in which both test -n and test -z are true

Tags:

linux

shell

#! /bin/bash

echo "Please input 2 nums: "

read a b

if [ -z $b ]; then
        echo b is zero !
fi

if [ -n $b ]; then
        echo b is non-zero !
fi

when run the script, only input 1 number, and leave the other empty, then b is supposed to be null. but the result is both echo is printed.

-laptop:~$ ./test.sh 
Pleaes input 2 nums: 
5 
b is zero !
b is non-zero !

b is both null and non-null ?! Could anyone comment on this ? Thanks !

~

like image 482
Yifan Zhang Avatar asked Feb 21 '23 07:02

Yifan Zhang


2 Answers

Replace

if [ -z $b ]; then

with

if [ -z "$b" ]; then

And do the same in the other if condition as well.

See http://tldp.org/LDP/abs/html/testconstructs.html for some interesting tests.

like image 122
Adam Liss Avatar answered Mar 02 '23 22:03

Adam Liss


It's all in the quotes. I don't remember where, but someone explained this recently on SO or USE - Without the quotes it doesn't actually do an empty/non-empty string test, but just checks that -n or -z are non-empty strings themselves. It's the same test that makes this possible:

$ var=-n
$ if [ "$var" ]
then
    echo whut
fi

Returns whut.

This means you can also have a sort of functional programming:

$ custom_test() {
    if [ "$1" "$2" ]
    then
        echo true
    else
        echo false
    fi
}

$ custom_test -z "$USER"
false
$ custom_test -n "$USER"
true
like image 20
l0b0 Avatar answered Mar 02 '23 23:03

l0b0