zsh:在for循环中向数组添加项时出现“未知文件属性”。

huangapple go评论67阅读模式
英文:

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

问题

适当的格式是在使用 zshfor 循环和变量时向数组添加元素的方式是:

当我尝试运行

declare -a numbers

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

我得到 unknown file attribute: 1

英文:

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.

答案1

得分: 0

在另一个情境中进行这项工作时,我发现在引用数组时不应该使用 $。而应该使用

numbers+=($i) 

编辑
根据 @chepner 的评论,我还声明了数组在 $numbers 上,而不是在 numbers 上。这在这个特定示例中并没有引起明显问题,因为该变量尚不存在,但我可以看到在更复杂的情况下可能会引发问题。

英文:

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.

huangapple
  • 本文由 发表于 2023年5月22日 23:08:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76307554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定