arraysbashshell

Convert an array stored in a string variable back to an array


This will create arr[0]=hy, arr[1]="hello man":

declare -a arr=(hy "hello man")

I have the 'hy "hello man"' this as whole string stored in variable such that:

echo "$var"
hy "hello man"

How can I split it back to an array? I tried IFS= IFS=" " readarray and all but array only results into arr[0]="hy "hello man"" and not arr[0]=hy, arr[1]="hello man"

Desired array:

arr[0]=hy arr[1]="hello man"

For testing purpose:

arg () { printf "%d args:" "$#"; [ "$#" -eq 0 ] || printf " <%s>" "$@"; echo; }

arg hy "hello man"
2 args: <hy> <hello man>

But

var='hy "hello man"'
arg $t
1 arg: <hy "hello man">

Is there a quoting trick that can help with my problem?


Solution

  • Is there a quoting trick that can help with my problem?

    Yes, place the double quotes around the whole array declaration (including the parens):

    var='hy "hello man"'
    unset arr; declare -a arr="($var)"   # or even:  declare -a "arr=($var)"
    

    This will restore the desired array (quotes inside $var must be syntactically correct, though):

    $ declare -p arr
    declare -a arr=([0]="hy" [1]="hello man")
    

    In contrast, putting the qoutes only around the variable would turn it into a single element:

    var='hy "hello man"'
    unset arr; declare -a arr=("$var")
    

    Resulting in the "wrong" array:

    $ declare -p arr
    declare -a arr=([0]="hy \"hello man\"")
    

    Tested with GNU bash, version 5.2.37(1)-release (x86_64-pc-linux-gnu)