英文:
zsh: "unknown file attribute" when adding an item to an array in a for loop
问题
适当的格式是在使用 zsh
的 for
循环和变量时向数组添加元素的方式是:
当我尝试运行
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论