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

Re: Bug with unset variables



On Wed, Nov 11, 2020 at 10:13 AM Roman Perepelitsa
<roman.perepelitsa@xxxxxxxxx> wrote:
>
> On Wed, Nov 11, 2020 at 4:57 PM Felipe Contreras
> <felipe.contreras@xxxxxxxxx> wrote:
> >
> > Hello,
> >
> > It's obvious what this code should do:
> >
> >   foo () {
> >     typeset var
> >     echo "var: '${var-other}'"
> >   }
>
> When foo is invoked, based on the documentation for typeset, I would
> expect it to print "var: ''".

My main concern is not the documentation of typeset, but useful code.

The primary reason for why typeset exists is to set the scope of a
variable. Especially so when using "local".

If I actually do something on the foo() function:

  typeset var
  [[ -n "$1" ]] && var=$1
  echo "var: '${var-other}'"

I would expect two things: 1) var is not set when I exit the function,
and 2) var is not set until I specifically set it.

I can get both in ksh and bash, but not in zsh. In zsh I have to
choose either 1) with typeset, or 2) by removing typeset.

How do you suggest I get both in zsh?

>     Except as noted below for control flags that change the behav-
>     ior, a parameter is created for each name that does not already
>     refer to one.
>
> And indeed that's how foo behaves when I invoke it in zsh 5.8.

It is possible to "create" a parameter without value (indeed that's
what happens in other shells), the documentation doesn't say anything
about assigning it a default empty string as value.

> > I also tried with the other unnamable shell, and the correct output is shown.

> From `help local`:
>
>     Create a local variable called NAME, and give it VALUE.
>
> As far as I can tell, there is no indication anywhere in the
> documentation that omitting =VALUE will cause `local` to not create a
> variable in bash.

The documentation makes it obvious that:

  local name

Creates a local variable called "name".

And:

  local name=value

Creates a local variable called "name", and gives it "value" as its value.

If you omit the value, then it doesn't assign it any value. As is the
case in countless languages; declaring a variable without specifying
any value assigns it the value of null (or "unset" in shell lingo).

> Do you believe the behavior of bash is expected while zsh behaves
> incorrectly? If so, why?

Yes, and ksh also behaves correctly.

As stated above, it's the only behavior that makes sense.

Otherwise you cannot declare a local variable that is unset.

Cheers.

-- 
Felipe Contreras




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