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