0

I have an array-like-string '[ "tag1", "tag2", "tag3" ]' and need to convert it to a bash array. How can this be achieved?

4
  • Looks like a JSON array. Commented Dec 10, 2015 at 7:00
  • ^^ Or python list :) Commented Dec 10, 2015 at 7:08
  • 1
    What is the source of this array-like string? (I ask because JSON/JavaScript arrays, Python arrays, Perl arrayrefs, etc., all have somewhat different edge-cases, so it would be best to write something with the right type in mind.) Commented Dec 10, 2015 at 7:35
  • $ line=[ "tag1", "tag2", "tag3" ] $ modline=${line//[,\"\[\]]/} $ arr=($modline) $ echo ${arr[0]} ${arr[1]} ${arr[2]} Commented Dec 10, 2015 at 7:53

2 Answers 2

3

As you know, arrays are declared in bash as follows:

arr=(one two three elements)

So let's try to tranform your input into a bash array. Without parsing the input, this might be very error prone and due to the use of eval, considerably insecure when variable user input would be processed.

Nevertheless, here's a starting point:

t='[ "tag1", "tag2", "tag3" ]'
# strip white space
t=${t// /}
# substitute , with space
t=${t//,/ }
# remove [ and ]
t=${t##[}
t=${t%]}
# create an array
eval a=($t)

When run on a console, this yields:

$ echo ${a[2]}
tag3
Sign up to request clarification or add additional context in comments.

1 Comment

For simple data, this could work. But for a bit more complicated data, like spaces or commas within array elements, this would fail. If the data is obtained from unknown source, you should not generally trust it.
0

The source format is similar to python list. Using python for intermediate processing:

$ src='[ "tag1", "tag2", "tag,\" 3" ]' # With embedded double quotes, spaces and comma for example.
$ IFS=$'\n' bash_array=($(python <<< 'a='"$src"$'\n''for t in a: print(t)'))
$ printf "%s\n" ${bash_array[@]}
tag1
tag2
tag,"3

1 Comment

Note that this still has the risk of code injection in python process.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.