13

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

ceving
  • 21,900
  • 13
  • 104
  • 178
Dan
  • 707
  • 3
  • 10
  • 18
  • See here: http://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash – ceving Nov 21 '13 at 13:06

1 Answers1

24

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
svckr
  • 791
  • 6
  • 11
  • awesome that worked. But how does it know what to split it by? – Dan Mar 22 '13 at 17:08
  • `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. – svckr Mar 22 '13 at 17:11