paul paul - 4 months ago 7
Bash Question

Add element into Array

I´m trying to add dinamiucally element into an array. Here my code

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


I´ve tried with an index, but same result

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


I´m doing something wrong here?

Regards.

Answer

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

echo "${fa[@]}"

should give you the entire array.

Reference

[ This ] should give you a nice description about bash arrays.

Comments