Convert a string into an array with bash, honoring quotes for grouping [duplicate]

This problem requires the use of xargs (it retains quoted strings together):

$ Str="This string has "a substring""
$ IFS=$'\n' arr=( $(xargs -n1 <<<"$Str") )
$ printf '<%s>\n' "${arr[@]}"
<This>
<string>
<has>
<a substring>

So, the element you need:

$ echo "${Tmp[3]}"
a substring

Please note that leading or trailing white space will be removed for “unquoted” items:

$ Str="  This    string    has "   a substring  ""
$ IFS=$'\n' arr=( $(xargs -n1 <<<"$Str") )
$ printf '<%s>\n' "${arr[@]}"
<This>
<string>
<has>
<   a substring  >

Leave a Comment