'How can I convert an array into a comma separated string?

I have an array and I am printing it like this:

echo "${data[*]}"

Output:

/QE-CI-RUN-71/workspace/QE-AU/57/testng-results_1.xml 
/QE-CI-RUN-71/workspace/QE-AU/57/testng-results_2.xml

I want to store the above output as a comma separated value. How can I achieve this in Bash?

The data array is dynamic, it may have any number of values.



Solution 1:[1]

To make it easier to localize the change of IFS, use a function:

join () {
  local IFS="$1"
  shift
  echo "$*"
}

join , "${data[@]}"

Solution 2:[2]

For ksh, try this!

foo=`echo $(echo ${data[@]}) | tr ' ' ','`

In this way you can control the delimiter by translating the space (default) to comma! (or any other you can think of) :)

Solution 3:[3]

If you want to separate with commas, make that be the first character in IFS:

data=( first second third )
IFS=,
echo "${data[*]}"

...emits:

first,second,third

Solution 4:[4]

printComma(){
    printf "%s," "${@:1:${#}-1}"
    printf "%s" "${@:${#}}"
}
printNewline(){
    printf "%s\n" "${@:1:${#}-1}"
    echo "${@:${#}}"
}
join () {
  local IFS="$1"
  shift
  echo "$*"
}
declare -a comma=(
    a
    b
    c
)
declare -a newline=(
    xyz
    abc
    def
    ghi
)
echo "\
Comma separated list $(printComma "${comma[@]}")
Newline list: $(printNewline "${newline[@]}")

Comma separated list $(join , "${comma[@]}")
Newline list: $(join \n "${newline[@]}")"
Comma separated list a,b,c
Newline list: xyz
abc
def
ghi

Comma separated list a,b,c
Newline list: xyznabcndefnghi

Solution 5:[5]

One-liner with IFS changed in a sub-command (safe):

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

Note: As IFS only takes first character, result would be comma separated list of values without space.

$ data=(file1 file2 file3)
$ (IFS=,; echo "${data[*]}")
file1,file2,file3

$ printf "%q" "$IFS"
$' \t\n'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chepner
Solution 2 Dan Dimacuha
Solution 3 Charles Duffy
Solution 4 Nico
Solution 5