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

Re: zsh adds empty string to local parameter when += is used



> On 20 January 2021 at 16:16 jamil bio <jamilbio20@xxxxxxxxx> wrote:
> func()
> {
>      local REPLY  files
> 
>      #unset files
>      for REPLY in file1 file2 file3
>      do
>          files+=( "$REPLY" )
>          echo "${#files[@]} -- ${files[@]}"
>      done
> }
> 
> func
> 
> 2 --  file1
> 3 --  file1 file2
> 4 --  file1 file2 file3

Yes, this is a bit weird, but it's explicable.

"local files" makes the variable "files" into a scalar, so if it's ever
referred to it will return an empty string.

The first time the function executes

  files+-( "$REPLY" )

it retrieves the existing $files.  At this point that's just an empty
string.  Then it adds the new element and assigns back to files.  It's
only at this point that files becomes an array.

You can fix the problem by declaring files as an array,

local -a files

pws




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