The case when both tests -n and test -z are correct

#! /bin/bash echo "Please input 2 nums: " read ab if [ -z $b ]; then echo b is zero ! fi if [ -n $b ]; then echo b is non-zero ! fi 

when running the script, enter only 1 number and leave the other empty, then b should be empty. but the result will be printed as an echo.

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

b is null and nonempty ?! Can anyone comment on this? Thanks!

~

+4
source share
3 answers

Replace

 if [ -z $b ]; then 

from

 if [ -z "$b" ]; then 

And do the same in another if .

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

+4
source

All this is in quotation marks. I don’t remember where, but someone explained this recently in SO or USE. Without quotes, it does not actually perform an empty / non-empty string test, but simply checks that -n or -z are not empty strings themselves. This is the same test that makes this possible:

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

Returns whut .

This means that you can also have some kind 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 
+3
source

The -n test requires the string to be enclosed in test brackets. However, using an unquoted string with ! -z ! -z or even just an incorrect line in test brackets usually works, however, this is an unsafe practice. Always specify a verified string.

 $ b='' $ [ -z $b ] && echo YES # after expansion: `[ -z ] && echo YES` <==> `test -z && echo YES` YES $ [ -n $b ] && echo YES # after expansion: `[ -n ] && echo YES` <==> `test -n && echo YES` YES 

test against nothing, enter true .

+1
source

Source: https://habr.com/ru/post/1208921/


All Articles