-2

I'm populating an array in a loop:

for k in one two three; do
  array+=( "$k" )
done
echo $k[0]  # should print one, instead prints one[0]
echo $k[1]  # should print two, instead prints one[1]

Why does this print one[0] instead of one?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Vak014
  • 39
  • 6
  • You can set your array using JSON_DATA[0]=… but to access it you require ${JSON_DATA[0]} rather than $JSON_DATA[0] etc. – borrible Jul 30 '19 at 09:52
  • Hi borrible, thank you! please post this in an answer and I will accept this. This worked for me. – Vak014 Jul 30 '19 at 09:55
  • See [What is the appropriate action when the answer to a question is edited into the question itself?](https://meta.stackoverflow.com/questions/267434/what-is-the-appropriate-action-when-the-answer-to-a-question-is-added-to-the-que) on [meta]. You're welcome to use the "Add an Answer" button to add an answer separately, even to your own question. – Charles Duffy Jul 30 '19 at 14:35

1 Answers1

0

You need to change your syntax when accessing arrays. You can set them using array[0]= but to access them you require ${array[0]} rather than $array[0] etc.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
borrible
  • 17,120
  • 7
  • 53
  • 75
  • If you truly believe that this is a full answer to the question the OP asked, you should be voting to close the question as a duplicate of [When do we need brackets around shell variables?](https://stackoverflow.com/questions/8748831), per the "Answer Well-Asked Questions" section of [How to Answer](https://stackoverflow.com/help/how-to-answer). – Charles Duffy Jul 30 '19 at 14:32