Bash split string into array using 4 simple methods


Written By - admin
Advertisement

How to create array from string with spaces? Or In bash split string into array? We can have a variable with strings separated by some delimiter, so how to split string into array by delimiter?

The main reason we split string into array is to iterate through the elements present in the array which is not possible in a variable.

 

Sample script with variable containing strings

For example in this script I have a variable myvar with some strings as element

# cat /tmp/split-string.sh
#!/bin/bash

myvar="string1 string2 string3"

echo "My array: $myvar"
echo "Number of elements in the array: ${#myvar[@]}"

Here if I want to iterate over individual element of the myvar variable, it is not possible because this will considered as a variable and not an array.
This we can verify by counting the number of elements in the myvar variable

When we execute the script, we see that number of elements in myvar is 1 even when we have three elements

# /tmp/split-string.sh
My array: string1 string2 string3
Number of elements in the array: 1

To overcome this we convert and split string into array. Now your variable can have strings or integers or some special characters, so depending upon your requirement you can choose different methods to convert string into an array. I will cover some of them with examples:

 

Method 1: Bash split string into array using parenthesis

Normally to define an array we use parenthesis (), so in bash to split string into array we will re-define our variable using open and closed parenthesis

Advertisement
# cat /tmp/split-string.sh
#!/bin/bash

myvar="string1 string2 string3"

# Redefine myvar to myarray using parenthesis
myarray=($myvar)

echo "My array: ${myarray[@]}"
echo "Number of elements in the array: ${#myarray[@]}"

Snippet from my terminal

Bash split string into array using 4 simple methods

Next execute the shell script. We see know we have 3 elements in the array

# /tmp/split-string.sh
My array: string1 string2 string3
Number of elements in the array: 3

 

Method 2: Bash split string into array using read

We can use read -a where each input string is an indexed as an array variable.
the default delimiter is considered as white space so we don't need any extra argument in this example:

# cat /tmp/split-string.sh
#!/bin/bash

myvar="string1 string2 string3"

# Storing as array into myarray
read -a myarray <<< $myvar

echo "My array: ${myarray[@]}"
echo "Number of elements in the array: ${#myarray[@]}"

Snippet from my terminal

Bash split string into array using 4 simple methods

Execute the script. Now the myarray contains 3 elements so bash split string into array was successful

# /tmp/split-string.sh
My array: string1 string2 string3
Number of elements in the array: 3

 

Method 3: Bash split string into array using delimiter

We can combine read with IFS (Internal Field Separator) to define a delimiter.
Assuming your variable contains strings separated by comma character instead of white space as we used in above examples
We can provide the delimiter value using IFS and create array from string with spaces

# cat /tmp/split-string.sh
#!/bin/bash

myvar="string1,string2,string3"

# Here comma is our delimiter value
IFS="," read -a myarray <<< $myvar

echo "My array: ${myarray[@]}"
echo "Number of elements in the array: ${#myarray[@]}"

Snippet from my terminal

Bash split string into array using 4 simple methods

Execute the shell script, and the variable is successfully converted into array and the strings can be iterated separately

# /tmp/split-string.sh
My array: string1 string2 string3
Number of elements in the array: 3

 

Advertisement

Method 4: Bash split string into array using tr

tr is a multi purpose tool. We will use this tool to convert comma character into white space and further using it under parenthesis from Method 1 to create array from string with spaces
So you can use this with any other delimiter, although it may not work under all use cases so you should verify this based on your requirement

# cat /tmp/split-string.sh
#!/bin/bash

myvar="string1,string2,string3"

# Change comma (,) to whitespace and add under braces
myarray=(`echo $myvar | tr ',' ' '`)

echo "My array: ${myarray[@]}"
echo "Number of elements in the array: ${#myarray[@]}"

Snippet from my terminal

Bash split string into array using 4 simple methods

Execute the shell script

# /tmp/split-string.sh
My array: string1 string2 string3
Number of elements in the array: 3

 

Some more examples to convert variable into array in bash

Based on your requirement you can choose the preferred method.

For example here I have a variable with newline as delimiter. So here I can use the first method. This will create array from string with spaces

# cat /tmp/split-string.sh
#!/bin/bash

myvar="string1
string2
string3"

myarray=($myvar)

echo "My array: ${myarray[@]}"
echo "Number of elements in the array: ${#myarray[@]}"

Execute the script. You can verify using the number of elements in the array

Advertisement
[root@rhel-8 ~]# /tmp/split-string.sh
My array: string1 string2 string3
Number of elements in the array: 3

We can now iterate through the elements which are part of the array in a loop

# cat /tmp/split-string.sh
#!/bin/bash

myvar="string1
string2
string3"

myarray=($myvar)
echo "My array: ${myarray[@]}"
echo "Number of elements in the array: ${#myarray[@]}"

for (( i=0; i<=${#myarray[@]}; i++ )); do
     echo "${myarray[$i]}"
done

Execute the script to verify

# /tmp/split-string.sh
My array: string1 string2 string3
Number of elements in the array: 3
string1
string2
string3

 

Lastly I hope the steps from the article for bash split string into array on Linux was helpful. So, let me know your suggestions and feedback using the comment section.

 

References:
man page of tr
man page of read
What is IFS in Bash?

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

5 thoughts on “Bash split string into array using 4 simple methods”

  1. I found Method 3 did not work for me… Here is the slightly modifed script:

    #!/bin/bash
    echo `/bin/bash --version`
    echo
    
    myvar="string1,string2,string3"
    
    # Here comma is our delimiter value
    IFS="," read -a myarray <<< $myvar
    
    echo "My array: ${myarray[@]}"
    echo "My array [0]:" ${myarray[0]}
    echo "Number of elements in the array: ${#myarray[@]}"

    (Modified to show the bash version in use and the contents of the first array entry…)

    Here is what I get:

    bash-3.2$ split-string.sh 
    split-string.sh 
    GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu) Copyright (C) 2005 Free Software Foundation, Inc.
    
    My array: string1 string2 string3
    My array [0]: string1 string2 string3
    Number of elements in the array: 1
    bash-3.2$ 

    It is possibly because my bash version is prehistoric, but I remain surprised that I get no error messages. Interesting the commas have gone when it lists My array[0] despite IFS initialisation…

    Reply
  2. Thanks for the great insights. Only one thing I noticed for change, in the for loop, I hope it should be i<${#myarray[@]},
    instead of i<=${#myarray[@]}
    as the index starts from zero.

    for (( i=0; i<${#myarray[@]}; i++ )); do
         echo "${myarray[$i]}"
    done
    Reply

Leave a Comment