Search code examples
arraysloopsscriptingzsh

zsh: "unknown file attribute" when adding an item to an array in a for loop


What is the proper format for adding an element to an array in zsh when using a for loop and variables?

When I try to run

declare -a $numbers

for i in {1..5}
do
  $numbers+=($i)
done

I get unknown file attribute: 1.


Solution

  • While working on this in another context, I discovered that I'm not supposed to use $ when referencing the array. Instead of

    $numbers+=($i)
    

    I need to use

    numbers+=($i)
    

    Edit
    Per the comment by @chepner, I was also declaring the array on $numbers instead of numbers. This didn't cause any obvious issues with this particular example because that variable didn't already exist, but I can see it causing problems in more complex situations.