Convert a text string in bash to array

Ayush Mishra picture Ayush Mishra · Oct 29, 2013 · Viewed 30.1k times · Source

How do i convert a string like this in BASH to an array in bash!

I have a string str which contains "title1 title2 title3 title4 title5" (space seperated titles)

I want the str to modified to an array which will store each title in each index.

Answer

devnull picture devnull · Oct 29, 2013

In order to convert the string to an array, say:

$ str="title1 title2 title3 title4 title5"
$ arr=( $str )

The shell would perform word splitting on spaces unless you quote the string.

In order to loop over the elements in the thus created array:

$ for i in "${arr[@]}"; do echo $i; done
title1
title2
title3
title4
title5