I have an array-like-string '[ "tag1", "tag2", "tag3" ]' and need to convert it to a bash array. How can this be achieved?
2 Answers
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
1 Comment
anishsane
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.
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
anishsane
Note that this still has the risk of code injection in python process.
$ line=[ "tag1", "tag2", "tag3" ] $ modline=${line//[,\"\[\]]/} $ arr=($modline) $ echo ${arr[0]} ${arr[1]} ${arr[2]}