Reading a space-delimited string into an array in Bash

Solution 1:

In order to convert a string into an array, please use

arr=($line)

or

read -a arr <<< $line

It is crucial not to use quotes since this does the trick.

Solution 2:

In: arr=( $line ). The "split" comes associated with "glob".
Wildcards (*,? and []) will be expanded to matching filenames.

The correct solution is only slightly more complex:

IFS=' ' read -a arr <<< "$line"

No globbing problem; the split character is set in $IFS, variables quoted.

Solution 3:

Try this:

arr=(`echo ${line}`);

Solution 4:

If you need parameter expansion, then try:

eval "arr=($line)"

For example, take the following code.

line='a b "c d" "*" *'
eval "arr=($line)"
for s in "${arr[@]}"; do 
    echo "$s"
done

If the current directory contained the files a.txt, b.txt and c.txt, then executing the code would produce the following output.

a
b
c d
*
a.txt
b.txt
c.txt