Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: PATCH: [[ -v varname ]]



2016-09-15 00:01:50 +0200, Oliver Kiddle:
> On 9 Sep, Stephane Chazelas wrote:
> > You guys may want to comment on the latest proposal there:
> > http://austingroupbugs.net/file_download.php?file_id=31&type=bug
> > as it would make zsh non-conformant.
> 
> One thing it also includes is the bash/ksh [[ -v ... ]] condition for
> checking if a particular variable is set. Zsh has the ${+varname} syntax
> which provides the same functionality in a different form. The following
> patch adds the ksh form for compatibility.
[...]

Note that there's a lot of variation between the ksh93 and bash
implementation of [[ -v ]] (though maybe not so much on the part
covered by POSIX), for instance on variables that have been
declared (or exported or marked readonly) with different types
but not assigned to (at least in zsh, declared/exported
variables are always given a default value), on arrays or hashs
that have no element (or no element of indice 0 or "0"; for a
hash in bash [[ -v h ]] returns true iff h[0] is set and in ksh
never ([[ -v h[@] ]] doesn't work either)).

Also note that in ksh/bash, it's only for variables, not other
types of parameters ([[ -v 0 ]], [[ -v "#" ]] return false).

See also:

$ a='b[0`uname>&2`]' bash -c '[[ -v $a ]]'
Linux

$ bash -c 'typeset -n a=b; [[ -v a ]]'; echo $?
1
$ b= bash -c 'typeset -n a=b; [[ -v a ]]'; echo $?
0

Spurious error message:

$ ksh -c 'typeset -T A=(a=a); A a; [[ -v a.x ]]'
ksh: x: is not an element of a

a.x returns false if $a has a x but that's a discipline (or
array/hash with 0 element not set).


In any case, it looks like your patch does the sensible thing in
all the cases I've tried except that [[ -v @ ]] returns false
(while [[ -v * ]] return true). No big deal as nobody would ever
want to do that.

What to do in zsh (where scalar and arrays are distinct types) for 

zsh -c 'a=1234; [[ -v a[1] ]]

is up to debate (currently returns false).

See also
https://unix.stackexchange.com/questions/212183/how-do-i-check-if-a-variable-exists-in-an-if-statement/246703#246703

-- 
Stephane



Messages sorted by: Reverse Date, Date, Thread, Author