How can I join elements of an array in Bash?


If I have an array like this in Bash:

FOO=( a b c )

How do I join the elements with commas? For example, producing a,b,c.

10/29/2018 5:15:31 PM

Accepted Answer

Rewriting solution by Pascal Pilz as a function in 100% pure Bash (no external commands):

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

For example,

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

Alternatively, we can use printf to support multi-character delimiters, using the idea by @gniourf_gniourf

function join_by { local d=$1; shift; echo -n "$1"; shift; printf "%s" "${@/#/$d}"; }

For example,

join_by , a b c #a,b,c
join_by ' , ' a b c #a , b , c
join_by ')|(' a b c #a)|(b)|(c
join_by ' %s ' a b c #a %s b %s c
join_by $'\n' a b c #a<newline>b<newline>c
join_by - a b c #a-b-c
join_by '\' a b c #a\b\c
8/30/2016 9:20:30 AM

Yet another solution:

foo=('foo bar' 'foo baz' 'bar baz')
bar=$(printf ",%s" "${foo[@]}")

echo $bar

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow