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

Re: Bug with unset variables



On Wed, Nov 11, 2020 at 9:42 PM Felipe Contreras
<felipe.contreras@xxxxxxxxx> wrote:
>
> >   typeset -i var
> >   echo $var
>
> In this case it might make sense to initialize to 0, since that's the
> only sensible default for an integer, but consider these:
>
>   typeset -i int
>   typeset -a array
>   typeset -A hash
>   typeset -F float
>
> In all these it should be obvious what would be the sensible default, but this:
>
>   typeset var

Both bash and zsh are consistent. Regardless of the presence or
absence of a storage specifier, bash leaves the variable unset while
zsh sets it to the "natural" value of the parameter's storage type. By
natural I mean neutral w.r.t. +=. If `typeset -i var` was setting
`var` to zero while `typeset var` was leaving it unset, that would be
inconsistent. In my opinion this would be worse than the behavior of
bash and zsh.

The fact that unset parameters are also called "null" in ksh/bash/zsh
invites confusion when comparing them to languages that can have
parameters with null *values*. Those null values are first-class
citizens. You can pass them as arguments to functions, store them in
arrays, etc. Shells don't have null *values*, they just have unset
parameters.

Most languages (in fact, all languages I know) either don't have the
notion of an unset variable with function scope, or automatically give
all declared variables values. The closest equivalent to ksh/bash/zsh
I'm aware of is elisp because it also has dynamic typing and dynamic
scope. elisp has the same notion of an unset variable as ksh/bash/zsh
(they are called void in elisp). You can declare local variables with
`let` and unset them with `makunbound`. These behave like `typeset`
and `unset` in zsh -- in order to create an unset variable with
function scope, you need to declare it and then unset. Declaring the
variable without value won't do.

In sum, what zsh does makes sense to me and feels natural and
consistent with other languages I know. That isn't to say that I
consider the behavior of ksh/bash incorrect. It's a bit surprising but
sensible. I could definitely get used to it. The strongest argument
for changing zsh is consistency with ksh and bash. The strongest
argument against it is that it'll break a lot of existing zsh code.
It's not my call but to me this looks like a no-go.

Roman.




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