bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Inconsistent string comparison operators n and z


From: Eric Blake
Subject: Re: Inconsistent string comparison operators n and z
Date: Mon, 09 Jun 2014 09:48:35 -0600
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Thunderbird/24.5.0

On 06/09/2014 07:11 AM, Thibault, Daniel wrote:

> Description:
>      The string comparison operators -n and -z are designed to be mutually
> complementary. ! -z should be interchangeable with -n and ! -n should be
> interchangeable with -z. But such is not the case. Consider these lines:

The bug is not in bash, but in your script.

> 
> $ if [   -z `pgrep pname` ]; then echo "not r" ; else echo "r" ; fi

Insufficient quoting.  If `pgrep pname` produces no output, then you are
running "[ -z ]", which has entirely different semantics (always true,
because the single-argument string -z is not empty).  You MEANT to write
"[ -z "`pgrep pname`" ]"; (or modernize your script, and use "[ -z
"$(pgrep pname)" ]", or use a bash-ism, and use "[[ -z $(pgrep pname) ]]")

> $ if [ ! -z `pgrep pname` ]; then echo "r" ; else echo "not r" ; fi
> $ if [   -n `pgrep pname` ]; then echo "r" ; else echo "not r" ; fi
> $ if [ ! -n `pgrep pname` ]; then echo "not r" ; else echo "r" ; fi

Same problem of insufficient quoting here.  Just as [ -z ] is always
true, so is [ -n ]; this behavior is required by POSIX.

> Turns out this is how the script needs to be written to work correctly:
> 
> $ if [   -z "`pgrep pname`" ]; then echo "not r" ; else echo "r" ; fi
> $ if [ ! -z "`pgrep pname`" ]; then echo "r" ; else echo "not r" ; fi
> $ if [   -n "`pgrep pname`" ]; then echo "r" ; else echo "not r" ; fi
> $ if [ ! -n "`pgrep pname`" ]; then echo "not r" ; else echo "r" ; fi

Glad you figured out your quoting bug.

-- 
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org

Attachment: signature.asc
Description: OpenPGP digital signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]