Bash: How to Split a String into an Array


You can use the following syntax in Bash to split a string into an array based on a specific delimiter:

IFS=' ' read -r -a my_array <<< "$my_string"

This particular example will split the string stored in the variable named my_string into an array named my_array.

Note that we used the IFS command (“internal field separator”) to specify that a single space should be used as the delimiter to split the string into individual elements in the array.

Once you have created this array, you can then use the following syntax to access individual elements in the array:

echo "${my_array[0]}"

The following example shows how to use this syntax in practice.

Example: How to Split a String into an Array in Bash

Suppose that we create a string variable in Bash named my_string that contains the following text:

  • “The Dallas Mavericks”

We can use the following syntax to split this string into an array, using a single space as a delimiter:

my_string="The Dallas Mavericks"
IFS=' ' read -r -a my_array <<< "$my_string" 

We can then use the following syntax to view each of the individual elements in the array:

for element in "${my_array[@]}"
do
    echo "$element"
done

The following screenshot shows how to use this syntax in practice:

Bash split string into an array

We can see that the string has been split into an array with three individual elements:

  • The
  • Dallas
  • Mavericks

We can also use bracket notation to access specific elements in the array.

For example, we can use the following syntax to access the first element in the array:

echo "${my_array[0]}"

The following screenshot shows how to use this syntax in practice:

Bash split string into array and access specific element

Notice that this returns “The”, which is the first element of the array.

You can uses similar syntax to access any element in the array.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Split a String into Multiple Variables
Bash: How to Split a String and Get Last Element
Bash: How to Split a String Using Multiple Delimiters

Leave a Reply