Add item to array

I am trying to dynamically add an element to 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 returns element1 .

I tried with the index but get the same result:

 fa[index]="$i" ((index++)) 

Am I doing something wrong here?

+7
bash shell
source share
1 answer

The problem is printing, i.e. echo $fa . This is equivalent to echo ${fa[0]} , which means the first element of the array, so you got element1

 echo "${fa[@]}" 

should provide you with the whole array.

Link

[This] should give you a good description of bash arrays.

+13
source share

All Articles