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

18,896

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 it's effects in the following command:

$ list=( first second third )
$ IFS=":" echo "${list[*]}"
first second third
$ IFS=":" ; echo "${list[*]}"
first:second:third
Share:
18,896
Dan
Author by

Dan

Updated on June 05, 2022

Comments

  • Dan
    Dan almost 2 years

    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

  • Dan
    Dan about 11 years
    awesome that worked. But how does it know what to split it by?
  • svckr
    svckr about 11 years
    IFS' default value is ` \t\n\r` or something like that. When assigning to an array using the ()-syntax everything between the parentheses gets expanded like parameters of a command, turning every "parameter" to an element of the array.