11

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?

1
  • A side-note, you may double check whether all the shells support fa+=("$i") style. Commented Jul 11, 2016 at 11:48

1 Answer 1

17

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.