How can I join elements of an array in Bash? How can I join elements of an array in Bash? bash bash

How can I join elements of an array in Bash?


A 100% pure Bash function that supports multi-character delimiters is:

function join_by { local d=${1-} f=${2-}; if shift 2; then printf %s "$f" "${@/#/$d}"; fi; }

For example,

join_by , a b c #a,b,cjoin_by ' , ' a b c #a , b , cjoin_by ')|(' a b c #a)|(b)|(cjoin_by ' %s ' a b c #a %s b %s cjoin_by $'\n' a b c #a<newline>b<newline>cjoin_by - a b c #a-b-cjoin_by '\' a b c #a\b\cjoin_by '-n' '-e' '-E' '-n' #-e-n-E-n-njoin_by , #join_by , a #a

The code above is based on the ideas by @gniourf_gniourf, @AdamKatz, @MattCowell, and @x-yuri. It works with options errexit (set -e) and nounset (set -u).

Alternatively, a simpler function that supports only a single character delimiter, would be:

function join_by { local IFS="$1"; shift; echo "$*"; }

For example,

join_by , a "b c" d #a,b c,djoin_by / var local tmp #var/local/tmpjoin_by , "${FOO[@]}" #a,b,c

This solution is based on Pascal Pilz's original suggestion.

A detailed explanation of the solutions previously proposed here can be found in "How to join() array elements in a bash script", an article by meleu at dev.to.


Yet another solution:

#!/bin/bashfoo=('foo bar' 'foo baz' 'bar baz')bar=$(printf ",%s" "${foo[@]}")bar=${bar:1}echo $bar

Edit: same but for multi-character variable length separator:

#!/bin/bashseparator=")|(" # e.g. constructing regex, pray it does not contain %sfoo=('foo bar' 'foo baz' 'bar baz')regex="$( printf "${separator}%s" "${foo[@]}" )"regex="${regex:${#separator}}" # remove leading separatorecho "${regex}"# Prints: foo bar)|(foo baz)|(bar baz


$ foo=(a "b c" d)$ bar=$(IFS=, ; echo "${foo[*]}")$ echo "$bar"a,b c,d