Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add element into Array

Tags:

bash

shell

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.

I've tried with an index, but I'm getting the same result:

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

Am I doing something wrong here?

like image 237
paul Avatar asked Jul 11 '16 11:07

paul


1 Answers

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.

like image 184
sjsam Avatar answered Oct 01 '22 14:10

sjsam