bash 将元素添加到数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38305993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add element into Array
提问by paul
I′m trying to dynamically add an element into an array:
我正在尝试将一个元素动态添加到数组中:
array=("element1" "element2" "element3")
fa=()
# now loop through the above array
for i in "${array[@]}"
do
fa+=("$i")
# or do whatever with individual element of the array
done
echo $fa
But it's returning element1
.
但它回来了element1
。
I've tried with an index, but I'm getting the same result:
我尝试使用索引,但得到相同的结果:
fa[index]="$i"
((index++))
Am I doing something wrong here?
我在这里做错了吗?
回答by sjsam
The problem is with printing ie echo $fa
. This is equivalent to echo ${fa[0]}
which means the first element of the array, so you gotelement1
问题出在打印 ie 上echo $fa
。这相当于echo ${fa[0]}
which 表示数组的第一个元素,所以你得到element1
echo "${fa[@]}"
should give you the entire array.
应该给你整个数组。
Reference
参考
[ This ]should give you a nice description about bash arrays.
[ 这个 ]应该给你一个关于 bash 数组的很好的描述。