Use the bash built-in printf ("print formatted") to easily format arguments and include separators.
printf format [argument]...
printfreuses theformatfor all subsequent arguments, which is useful when passing an argument list of non-fixed length. Also works with empty arrays.- Use the
@subscript and double quotes when expanding the array, to ensurebash/printfcan keep arguments apart. - Since you want to "join" the array, an issue is that the last (or first, if you flip delimiter order) item will have an extra delimiter. Luckily it's easy to replace or remove this extra delimiter, for example using
sed.
# NOTE: print MY_ARRAY with a comma after each entry.
printf '%s,' "${MY_ARRAY[@]}"
Since you want to "join" the array, an issue is that the last (or first, if you flip delimiter order) item will have an extra delimiter. Luckily it's easy to replace or remove this extra delimiter, for example using sed.
# NOTE: replace the last comma with newline.
printf '%s,' "${MY_ARRAY[@]}" | sed --unbuffered 's/,$/\n/'
Here's an printf rewrite of your sample code, avoidingwith minor fixes. Avoiding to touch IFS, with minor fixes:which can have side-effects unless narrowly scoped.
#!/bin/bash
MY_ARRAY=("Some string" "Another string")
function join { local SEPARATOR="$1"; shift; printf "%s${SEPARATOR}" "$@" | sed --unbuffered "s/${SEPARATOR}$//"; }
join "," "${MY_ARRAY[@]}"
The output is Some string,Another string.