0

How do I iterate over square brackets type data:

I have written this script:

#!/usr/bin/env bash

# This is a external variable I have in Bash file which has the data already
echo $sample_data_set

for i in "${sample_data_set[@]}"
do
   : 
   echo $i
done

And I need to iterate over $sample_data_set. Am I missing something?

I am getting output:

[ "test1", "test2", "test3", "test4" ]
test.sh: 6: Bad substitution
Thompson
  • 1,954
  • 10
  • 33
  • 58
  • assuming `sample_data_set` is supposed to be an array ... try `sample_data_set=( test1 test2 test3 test4 )`; the `for` loop should then work correctly (ie, it should print `test1\ntest2\ntest3\ntest4\n` – markp-fuso Sep 21 '20 at 15:29
  • I have this output [ "test1", "test2", "test3", "test4" ] coming from separate shell script, which I can't modify. I just provided here to demonstrate that actually – Thompson Sep 21 '20 at 15:34
  • OK, so it's **not** an array, which means `"${sample_data_set[@]}" (an array reference) is not going to work; will there always be 4x elements? could there be more? is there an expected max number of elements? – markp-fuso Sep 21 '20 at 15:38
  • Yes, this is dynamic variable that can have many about 10 or 20 values too. – Thompson Sep 21 '20 at 15:39
  • 3
    The question is more like "how can I parse a string `[ "foo", "bar", "baz" ]` with up to 20 values as a Bash array?", right? – Benjamin W. Sep 21 '20 at 15:47
  • Yes, correct. you're right. But that seems to be an array. And i want to iterate through it so that I can use each value from that array. And that's not limited to 20 values. It is a dynamic Array variable. – Thompson Sep 21 '20 at 15:47
  • You have a JSON value. You'll probably want to use `jq`, but depending on what exactly you need to do with each element of the array, `bash` is probably not the right language to use. – chepner Sep 21 '20 at 15:52
  • @Thompson, it's a **JSON** array, but it's absolutely not a **bash** array. – Charles Duffy Sep 21 '20 at 15:52
  • 1
    See https://stackoverflow.com/questions/54087481/assigning-an-array-parsed-with-jq-to-bash-script-array for guidance on converting between the two. (Some of those answers are better than others; I'm still looking for something I really like). – Charles Duffy Sep 21 '20 at 15:53
  • 1
    ...here we go: https://stackoverflow.com/questions/62815281/convert-json-array-to-bash-array-preserving-whitespaces is on-point. Use the `-r` argument to jq when what you're extracting are strings and you don't want them quoted as JSON. – Charles Duffy Sep 21 '20 at 15:55

0 Answers0