#! /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 !
~
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With