Nikola Novak Nikola Novak - 1 month ago 7
Bash Question

In bash, how do I convert a space-delimited string into an array?

I have a variable which contains a space-delimited string,

line="1 1.50 string"


I want to split that string with space as a delimiter and store the result in an array, so that the following:

echo ${arr[0]}
echo ${arr[1]}
echo ${arr[2]}


outputs

1
1.50
string


Somewhere I found a solution which doesn't work:

arr=$(echo ${line})


If I run the echo statements above after this, I get:

1 1.50 string
[empty line]
[empty line]


I also tried

IFS=" "
arr=$(echo ${line})


with the same result. Can someone help, please?

kev kev
Answer
arr=($line)

or

read -a arr <<<$line