linuxarraysbashshell

Bash script to convert a string with space delimited tokens to an array


I have a string

echo $STRING

which gives

first second third fourth fifth

basically a list separated spaces.

how do i take that string and make it an array so that

array[0] = first
array[1] = second

etc..

I have tried

IFS=' ' read -a list <<< $STRING

but then when i do an

echo ${list[@]}

it only prints out "first" and nothing else


Solution

  • It's simple actually:

    list=( $STRING )
    

    Or more verbosely:

    declare -a list=( $STRING )
    

    PS: You can't export IFS and use the new value in the same command. You have to declare it first, then use its effects in the following command:

    $ list=( first second third )
    $ IFS=":" echo "${list[*]}"
    first second third
    $ IFS=":" ; echo "${list[*]}"
    first:second:third
    

    Notice that the last example will change IFS to ":" until you change it again, or the shell exits. Usually you want to use a subshell, or save the original value of IFS so you can restore it afterwards.