Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash empty string comparison Issue

Tags:

linux

bash

I know i can test a string whether it is empty with -z and test a string whether it is non empty with -n. So I write a script in ubuntu 10.10:

#!/bin/bash
A=
test -z $A && echo "A is empty"
test -n $A && echo "A is non empty"
test $A && echo "A is non empty" 

str=""
test -z $str && echo "str is empty"
test -n $str && echo "str is non empty"
test $str && echo "str is non empty" 

To my surprise, it output :

A is empty
A is non empty
str is empty
str is non empty

which I thing it should be

A is empty
str is empty

Could any Linux expert explain why ?

Thank you.

like image 228
爱国者 Avatar asked Aug 20 '26 14:08

爱国者


2 Answers

This is a consequence of the way Bash command lines are parsed. Variable substitution happens before constructing the (rudimentary) syntax tree, so the -n operator doesn't get an empty string as an argument, it gets no argument at all! In general, you must enclose any variable reference into "" unless you can be positively sure it isn't empty, precisely to avoid this and similar problems

like image 101
Kilian Foth Avatar answered Aug 23 '26 12:08

Kilian Foth


The 'problem' comes from this:

$ test -n && echo "Oh, this is echoed."
Oh, this is echoed.

i.e. test -n without an argument returns 0/ok.

Change that to:

$ test -n "$A" && echo "A is non empty"

and you'll get the result you expect.

like image 45
Mat Avatar answered Aug 23 '26 12:08

Mat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!