Bash: How to Split a String into Multiple Variables


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

IFS=- read -r var1 var2 var3 <<< My-Cool-String

This particular example will split the string “My-Cool-String” into three variables named var1, var2 and var3 based on where the dashes occur in the string.

Note that we used the syntax IFS=- to specify that a dash should be used as the delimiter to split the string into individual variables.

Note: In Bash, IFS stands for “internal field separator” and can be used to specify the separator (or “delimiter”) that should be used when reading a string.

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

Example: How to Split a String into Multiple Variables in Bash

Suppose that we would like to split the string My-Cool-String into the following three variables:

  • var1 = My
  • var2 = Cool
  • var3 = String

We can use the following syntax to do so:

IFS=- read -r var1 var2 var3 <<< My-Cool-String

We can then use the following syntax to view the contents of each newly created variable:

echo "$var1"
echo "$var2"
echo "$var3"

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

Bash split string into multiple variables

Notice that when we use the echo statement to view each variable, we can confirm that each of the variables holds one of the three substrings from the original string.

Note: If you attempt to create more variables than the number of strings produced after the split, any extra variables will simply be empty.

Related Tutorials

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

Bash: How to Extract First Number from a String
Bash: How to Count Number of Words in String
Bash: How to Count Number of Characters in String
Bash: How to Check if String Starts with Specific Value

Leave a Reply