Monday, October 10, 2022

[SOLVED] Why does `local x` inside a zsh for loop output `x=y`?

Issue

Given

for v in a b c; do
  local y
  y=$v
done

Zsh outputs the following automatically:

y=a
y=b

Why does this occur? What is the use? It wont output y=c, so it's not reliably eval'able but there must be a reason for this behaviour.


Solution

In the zshbuiltins(1) manpage, we have

  • local -> "Same as typeset ..."

  • typeset -> ...

    If the shell option TYPESET_SILENT is not set, for each remaining name that refers to a parameter that is already set, the name and value of the parameter are printed in the form of an assignment. Nothing is printed for newly-created parameters, or when any attribute flags listed below are given along with the name.

It appears for the iteration where v=b and v=c, local y is reporting on the value of y set in the previous iteration.

I'm not a zsh expert, but if it's like bash, then there are only 2 variable scopes: global and function-local. There is no concept of a variable local to a loop.

You should

  • take local y out of the loop so it does not get executed needlessly repeatedly, or
  • set the aforementioned shell option to make local shut up: setopt TYPESET_SILENT


Answered By - glenn jackman
Answer Checked By - Pedro (WPSolving Volunteer)