If you want to output a string consisting of the elements of an array delimited by a particular character, then use
words=(a b c)
( IFS=,; printf '%s\n' "${words[*]}" )
Using *
in place of @
in "${words[*]}"
will create a single string out of the concatenation of all elements of the array words
. The elements will be delimited by the first character of $IFS
, which is why we set this to a comma before doing the expansion.
I set IFS
in a subshell to avoid inadvertently setting it for any other operation than the single expansion needed to create the comma-delimited string for the printf
call.
Instead of using a subshell to set IFS
locally, you may instead set it and then reset it:
words=(a b c)
IFS=,$IFS
printf '%s\n' "${words[*]}"
IFS=${IFS#?}
This first adds a comma as the first character of $IFS
, retaining the old value of the variable as the characters after the comma.
The parameter substitution ${IFS#?}
would delete the first character (the comma that we added).