Bash: How to Join Elements from Array into Delimited String


Often in Bash you may want to join all of the elements from an array into a single string with a specific delimiter.

You can use the following syntax to do so:

my_string=$(IFS=, ; echo "${my_array[*]}")

This particular example will join all of the elements from the array named my_array into a single string named my_string, in which each element is separated using a comma.

Note that we use the IFS (“internal field separator”) command to specify the delimiter that should be used when joining the elements together into a string.

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

Example: How to Join Elements from Array into Delimited String in Bash

Suppose that create a variable named my_array in Bash that contains the names of various basketball teams:

my_array=(Mavs Hawks Spurs Kings Celtics)

Suppose that we would like to join all of the elements of this array into a single string in which each element is separated by a comma.

We can use the following syntax to do so:

my_string=$(IFS=, ; echo "${my_array[*]}")

echo $my_string

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

Bash join elements from array into delimited string

When we use the echo statement to view the new string variable we can see that it contains all of the elements from the array, joined together using a comma as a separator.

Note that you can specify any separator that you’d like following the IFS command.

For example, you could use the following syntax to join together all of the elements into a single string using a dash as a separator instead:

my_string=$(IFS=- ; echo "${my_array[*]}")

echo $my_string

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

Notice that the string variable now contains all of the elements from the array joined together, using a dash as a separator.

Feel free to use similar syntax to join together the elements from your own array into a single string.

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 Split a String into Multiple Variables
Bash: How to Count Number of Words in String
Bash: How to Count Number of Characters in String

Leave a Reply