How to Convert String into Array in Bash [8 Methods]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

You can use the following methods to convert a string into array in Bash:

  1. Using parenthesis (): array=($string)
  2. Using read command: read -a array <<< "$string"
  3. Using mapfile command: mapfile -t array < <(printf '%s\n' "$string" | tr ' ' '\n')
  4. Using for loop: for word in $string; do array+=("$word"); done

Converting a string into an array in Bash is the process of breaking down a single string into multiple elements and storing each element separately in an array data structure that allows working with the individual parts of a string more effectively. This article discusses 8 methods to convert a string into an array in Bash by splitting it into individual parts based on a condition and storing them in the array as elements. It shows the conversion of single as well as multiline strings into arrays in Bash.

1. Using Parenthesis ()

The most simple method to split a string and convert it into a Bash array is to use parenthesis () in the syntactical format array=($string). This simply defines the elements inside the parenthesis as elements of array separated by whitespace characters.

Here’s an example to convert a string into an array in Bash using array=($string):

#!/bin/bash

# Defining a string
string="audi bmw accord yamaha jaguar"

# Splitting the string into an array
cars=($string)

# Output the array and its length
echo "My array: ${cars[@]}"
echo "Number of elements in the array: ${#cars[@]}"
EXPLANATION

In the above, the expression cars=($string) splits the string by spaces and stores the words (audi bmw accord yamaha jaguar) as 5 individual elements of the cars array and this is verified after printing the length (5) of the array using the echo command on the terminal.

bash string to array using parenthesis
Note: To split an array into a string by a specified delimiter other than whitespace, define the delimiter using the IFS=’delimiter’ and Bash will split the string based on this delimiter into an array.

2. Using the “read” Command

The read command is a useful tool in Bash scripting to access contents from external resources and store them in an array and this is powerful in reading a string and converting it into an array in Bash. Here’s how:

#!/bin/bash
#string
string='Bash is scripting language'
#declare empty array for element storage from string
declare -a array=()

#split string to array using read command
read -a array <<< "$string"

#print items and length to verify the string to array conversion
echo "some elements:${array[2]} ${array[3]}"
echo "all elements: ${array[@]}"
echo "array length: ${#array[@]}"
EXPLANATION

In the above script, after defining the string, ‘Bash is scripting language’, an empty array is declared using declare -a array=(). Then the “read” command with the -a flag takes the string as its input field from the here-string, <<< “$string“, and splits it based on whitespace characters (the default delimiter) to read it into an array-type variable to convert the string to an array. Thus, printing the array length shows the success of this string-to-array conversion operation.

read command to conver t string to array

3. Using IFS (Internal Field Separator)

The IFS (Internal Field Separator) is a powerful tool that allows the defining of a specific character as a delimiter in splitting a string into separate words and converting it to an array in Bash by storing them as elements. In using the IFS value with the read command, Bash splits the given string automatically based on the IFS value (the delimiter) and converts it into an array. Here’s an example:

#!/bin/bash

#the string
string='apple grape dragon'

#split string into array by space 
IFS=' ' read -a array <<< "$string"

#print array items and length
echo "array: ${array[*]}"
echo "array length: ${#array[@]}"
EXPLANATION

In the above, the code IFS=' ' is set to whitespace character, and the read -a array <<< "$string" command splits the string into 3 parts apple grape, and dragon. Then these 3 words are stored in the array variable which effectively converts the string to a Bash array. After printing the array elements and length, it’s clear that the string-to-array conversion was successful.

space delimiter to convert string to array

Using IFS with Comma as Delimiter

The previous example set IFS=’ ‘ which treats whitespaces as delimiters in converting strings to arrays in Bash. In addition, IFS=’, ‘ can treat a comma as a delimiter to convert a string into an array like the example below:

#!/bin/bash

#the string
string='grapes,orange,apple,kiwi,peach'
echo "string: $string"
echo 
#split string into array by comma
IFS=',' read -a array <<< "$string"

#print array items and length
echo "array: ${array[*]}"
echo "array length: ${#array[@]}"

comma to split and convert string to array

Using IFS with Colon as Delimiter

Setting a colon as the delimiter using IFS=’:’ tells the read command to convert a string into an array by separating each element after a colon. Here’s how:

#!/bin/bash

#the string
string='grapes:orange:apple:kiwi:peach'
echo “string: $string”
echo

#split string into array by colon 
IFS=':' read -a array <<< "$string"

#print array items and length
echo "array: ${array[*]}"
echo "array length: ${#array[@]}"

colon to convert string to bash array

Using IFS with Custom Delimiter

Similarly, Setting any custom character as a delimiter using IFS assists Bash in converting strings into arrays by making the character separate the words or string tokens.

Following is an example of converting a string into a Bash array where the “forward slash (/)” becomes the delimiter:

#!/bin/bash

#the string
string='grapes/orange/apple'
echo “string: $string”
echo

#split string into array by forward slash
IFS='/' read -a array <<< "$string"

#print array items and length
echo "array: ${array[*]}"
echo "array length: ${#array[@]}"

custom delimiter convert s string to array

4. Using “mapfile” Command

The mapfile command facilitates the reading of a string and converts it into an array in Bash using the syntax mapfile -t array < <(printf '%s\n' "$string" | tr ' ' '\n'). Let’s see the “mapfile” command in action in converting a string into an array in Bash:

#!bin/bash
string="apple banana orange"
mapfile -t array < <(printf '%s\n' "$string" | tr ' ' '\n')

# Print the resulting array
echo "${array[@]}"
echo "${#array[@]}"
EXPLANATION

The script starts with a string containing three words: “apple banana orange”. The printf '%s\n' "$string" command prints each word on a separate line, and tr ' ' '\n' changes spaces to newlines, effectively splitting the string into individual lines. Then, mapfile -t array reads these lines, removing trailing newline characters, and storing them as elements of the array which is evident after printing the array length. 

mapfile converts string to array

5. Using “readarray” Command

The readarray command is another form of the mapfile command. Both are Bash commands that can be useful in reading a string and converting it into an array by splitting it into individual parts. Here’s how to convert a string into an array in Bash using the “readarray” command:

#!/bin/bash

#the string with space separated words
string="apple banana orange kiwi"

#convert string with readarray and store in array variable
readarray -t fruit < <(printf '%s\n' "$string" | tr ' ' '\n')

# Print the resulting array and length
echo "items: ${fruit[@]}"
echo "array length: ${#fruit[@]}"
EXPLANATION

The script uses printf '%s\n' "$string" to print each word of the given string on a separate line. The tr ' ' '\n' command translates each space character into a newline character, effectively splitting the string into individual lines.The readarray -t fruit command reads these lines and stores them as elements of the fruit array where each word is an element of the array.

string to array by readarray command

6. Using “tr” Command

The Linux tr command stands for translate and it’s primarily used to translate or delete characters within a stream of data. Additionally, the tr command is handy in converting a string into an array in Bash.

Here’s an example of the tr command to replace space with a newline character (\n) to effectively split a string into separate lines and convert it to an array:

#!/bin/bash
# define a string and print
string="world war 3"
echo "string: $string"
echo 

# Split the string into array elements using tr
array=($(echo "$string" | tr ' ' '\n'))

# Print the array elements and length
echo "array: ${array[@]}"
echo "length: ${#array[@]}"
EXPLANATION

In the above, the echo "$string" command prints the string variable contents and tr ' ' '\n' translates characters and, in this case, replaces each space with newline characters to split the string into parts which are then stored by the array variable using array=($(…)). Finally, printing the array items and length verifies the string-to-array conversion process.

tr command splits string to array

7. Using “for” Loop

The Bash for loop is an effective tool in terms of accessing array elements iteratively for data manipulation. However, the for loop allows the conversion of strings to arrays by iterating over string characters and deciding how to split it for array conversion with more control. Here’s how:

#!/bin/bash

string="apple banana orange"
array=()
for word in $string; do
    array+=("$word")
done
echo "elements: ${array[@]}"
echo "length: ${#array[@]}"
EXPLANATION

In the above, after defining a string and an empty array, the loop for word in $string iterates over each whitespaced word of the string (apple banana orange) and the array+=("$word") expression appends each word as elements to array; effectively converting a string to an array.

for loop splits and converts string to array

8. Using Loop with Regular Expressions (Regex)

Combining “regular expressions with loops” provides a powerful and flexible way of precisely converting strings to bash arrays by iterating over matches of given patterns. Here’s an example:

#!/bin/bash

# Define a string with mixed content
string="apple123 banana456 orange789"

# Use a loop with regex to "bash split string into array"
while [[ $string =~ ([a-zA-Z]+)([0-9]+) ]]; do
    myvar+=("${BASH_REMATCH[1]}")        # Adding matched word to the array
    string=${string#*${BASH_REMATCH[1]}} # Removing the matched part from the beginning of the string
done

# Output the array and its length
echo "My array: ${myvar[@]}"
echo "Number of elements in the array: ${#myvar[@]}"
EXPLANATION

In the above, after defining a string with value “apple123 banana456 orange789”, the regex pattern ([a-zA-Z]+)([0-9]+) looks for patterns of letters followed by numbers and if the proper match is found then, it’s stored to the array called myvar as an element. After a match, the matched part is removed from the beginning of the string for further iteration to find other matches.

loop with regex to convert string to array

Convert String to Array Based on Multiple Delimiters

Apart from converting strings into arrays based on a single delimiter, Bash is also capable of converting the string into an array by splitting it with multiple delimiters at once. See the script below for a clearer understanding of how to convert strings into arrays based on multiple delimiters:

#!/bin/bash

# Define a string
string="apple,banana;orange|grape"

# Set the IFS to multiple delimiters
IFS=',;|'

# Use read to bash split string into array
read -a my_arr <<< "$string"

# Output the array and its length
echo "elements: ${my_arr[@]}"
echo "length: ${#my_arr[@]}"
EXPLANATION

In the above, a string is defined and the individual parts are separated using comma, semicolon, and pipe. Now, the expression IFS=',;|' sets 3 characters (comma semicolon pipe) as delimiters and the read command splits the string based on each delimiter to store the elements in the array named my_arr  to the string to an array which is evident after printing the elements and array length.

string to array by multiple delimiters

Converting Multiline Strings into an Array in Bash

It is also possible to convert a multiline string in Bash and convert it into an array. Just specify the IFS as the newline character with IFS=$’\n’  to split the string into individual parts and store them as elements in an array-type variable. Here’s an example to convert  multiline strings into Bash arrays:

#!/bin/bash

# Define a multi-line string
multiline_string="apple
banana
orange"

# Set the IFS to newline
IFS=$'\n'

# Use read to bash convert string to array within a loop
while read -r line; do
    array+=("$line")
done <<< "$multiline_string"

# Output the array and its length
echo "array items: ${array[@]}"
echo "array length: ${#array[@]}"
EXPLANATION

The above code first defines a 3-line string and the IFS is set to newline character (\n) to split the multiline string using newline as the delimiter. Finally, the while loop iterates over each line and reads them using the read command along with appending each line as array elements using array+=("$line"). This effectively converts the given string to a Bash array and printing the array length successfully reflects the change.

multiline strings to bash array

Practice Problems to Convert String into A Bash Array

Try these problems out and share the solutions in the comment section:

  1. Convert the string=’hello, world, universe’ into an array by delimiter comma using parenthesis [the syntax is array=($string)].
  2. Convert the string=’hello, world; universe/ multiverse’ into an array by multiple delimiters comma, semicolon, and forward slash using parenthesis [the syntax is array=($string)].
  3. Suppose, you have a string, number=”1,2;3/4″. Now convert it into an array in a way that the array should have 3 elements 1, 2, and 3/4.

Conclusion

This article discusses 8 different methods of how to convert a string into an array in Bash. It mentions standard array syntax, and commands like read, mapfile, readarray, tr, etc. to split a string and convert it into an array in Bash. Moreover, it sheds light on for loop to convert a string into an array iteratively. Furthermore, it discusses string-to-array conversion by splitting multiline strings as well including handling single and multiple delimiters.

People Also Ask

How to convert a Bash array into a string?

To convert a Bash array into a string, join the individual array elements by a specific delimiter using IFS and store the string in a variable using the syntax string=$(echo "${arr[*]}"). This captures the output of the echo command and stores it in the string variable to effectively join the elements into a single string separated by the whitespaces by default.

How to declare an array of strings in Bash?

To declare an array of strings in Bash, give the array a name, follow that name by parenthesis (), and inside the parenthesis enter strings with single or double quotes (adding no quotes also treats elements as strings by default in Bash) while adding no commas around them. The syntax is array=(“elements separated by spaces”). For instance, the code cars=("bmw" "audi" "lexus") declares an array called cars with 3 string-type elements.

How to convert a comma-separated string into an array in Bash?

To convert a comma-separated string into a Bash array, set the delimiter to comma using IFS=’,’ and successfully split the string into parts to store them in an array. For example, to convert the string str='hello, world' by a comma, use the code IFS=',' read -a my_array <<< "$str". This will treat the words hello and world as separate entities (since the delimiter is comma) and store them as elements of the array called my_array.

How do I split a string into an array in Bash?

You can split a string into an array in Bash by using the “read” command within the commandread -a arr <<< "$string". This reads the input string and assigns the words (separated by spaces by default) to the array-type variable named arr. For example, if the string contains  ‘apple banana orange’, the command splits each word and stores it as contiguous elements of arr. So, after printing the length of arr using echo ${#ar[@]}, the result will be 3 since the array now has 3 items.

What is the role of IFS in converting a string to an array in Bash?

The IFS (Internal Field Separator) in Bash recognizes how Bash determines word boundaries within strings. In converting a string into an array, it’s pivotal to specify the delimiter to split the individual elements from the string. By setting IFS to a desired delimiter such as a comma or colon, Bash knows where to split the given string using the read command or for loop, for example, into a separate entity and store them as array elements to successfully convert the string to an array.

Can I convert a string into a Bash array without using the read command and the IFS?

Yes, you can. Use parenthesis within the syntax my_array=($my_string). This will split my_string into separate words and store them in an array called my_array, by using whitespaces as delimiters and convert the string into an array. For example, to convert the string str= 'apple banana orange' into an array named “my_arr” without using the “read” command and “IFS”, use the code my_arr=($str).

Is it possible to split a string into an array by a specific delimiter in Bash?

Certainly. Just use the read command with the IFS (Internal Field Separator) set to the specific delimiter to split the string into an array in Bash. Take the string str='apple]grape]dragon' for example. The code IFS='] ' read -a array <<< "$str" splits the words by the delimiter ] set by IFS and stores them as array elements. This is how it is possible to split a string into an array based on a specific delimiter in Bash.

How do you convert an array into a multiline string in Bash?

To convert a Bash array into a multiline string in Bash, define an empty string variable such as multiline_string="", iterate over the array elements using the loop for element in "${array[@]}" and concatenate each array element with a newline character (\n) to append them to the multiline string variable using multiline_string+="$element\n". Finally, use the command echo -e "$multiline_string" to preserve each newline character to print the multiline string on the screen. For example, after converting an array lines=(apple banana orange grape) into a string containing multiple lines.

Related Articles


<< Go Back to Array Operations in Bash | Bash Array | Bash Scripting Tutorial

Rate this post
Md Masrur Ul Alam

Assalamu Alaikum, I’m Md Masrur Ul Alam, currently working as a Linux OS Content Developer Executive at SOFTEKO. I completed my Bachelor's degree in Electronics and Communication Engineering (ECE)from Khulna University of Engineering & Technology (KUET). With an inquisitive mind, I have always had a keen eye for Science and Technolgy based research and education. I strongly hope this entity leverages the success of my effort in developing engaging yet seasoned content on Linux and contributing to the wealth of technical knowledge. Read Full Bio

Leave a Comment