Thursday, June 30, 2011

Convert a space-separated string into array in Bash

A previous post showed how Emacs can read an environment variable (containing space-separated project directories) to set up multiple projects. To process the same environment variable in Bash, we will need a way of spliting a space-separated string into an array of the space-separated elements. The following script accomplishes this task.

declare -a array
space_sep_string="aa bb cc dd"
array=(${space_sep_string// / })

for i in ${array[@]}; do
    echo $i


Staef said...

array=(${space_sep_string// / })
you forgot the parenthese ;)

tsengf said...

Thanks Staef for catching the mistake.

Joe Pedestrian said...

Thanks for good hint!

herculesgr8 said...

array=( $(echo space_sep_string) )