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: Dennis Williamson
Subject: Re: Inconsistent string comparison operators n and z
Date: Mon, 9 Jun 2014 10:47:36 -0500

On Jun 9, 2014 10:41 AM, "Thibault, Daniel" <Daniel.Thibault@drdc-rddc.gc.ca>
wrote:
>
> Configuration Information [Automatically generated, do not change]:
> Machine: x86_64
> OS: linux-gnu
> Compiler: gcc
> Compilation CFLAGS:  -DPROGRAM='bash' -DCONF_HOSTTYPE='x86_64'
-DCONF_OSTYPE='linux-gnu' -DCONF_MACHTYPE='x86_64-pc-linux-gnu'
-DCONF_VENDOR='pc' -DLOCALEDIR='/usr/share/locale' -DPACKAGE='bash' -DSHELL
-DHAVE_CONFIG_H   -I.  -I../bash -I../bash/include -I../bash/lib
 -D_FORTIFY_SOURCE=2 -g -O2 -fstack-protector --param=ssp-buffer-size=4
-Wformat -Wformat-security -Werror=format-security -Wall
> uname output: Linux sds-dut-vb 3.9.3 #1 SMP Mon Mar 24 18:48:39 EDT 2014
x86_64 x86_64 x86_64 GNU/Linux
> Machine Type: x86_64-pc-linux-gnu
>
> Bash Version: 4.2
> Patch Level: 25
> Release Status: release
>
> 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:
>
> $ 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
>
> They should be equivalent but are not: -z correctly detects the process's
> presence or absence, while -n returns true even when the process is not
> running.
>
> 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
>
> Repeat-By:
>      See the examples above.
>

If you use single square brackets, you must quote the argument. For example:

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

etc. And you should use $() instead of backticks.

In Bash, you should use double square brackets. Please see
http://stackoverflow.com/a/3870055/26428


reply via email to

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