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
.
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
.
Combine best of all worlds so far with following idea.
This little masterpiece is
Examples:
My attempt.
Using variable indirection to refer directly to an array also works. Named references can also be used, but they only became available in 4.3.
The advantage of using this form of a function is that you can have the separator optional (defaults to the first character of default
IFS
, which is a space; perhaps make it an empty string if you like), and it avoids expanding values twice (first when passed as parameters, and second as"$@"
inside the function).This solution also doesn't require the user to call the function inside a command substitution - which summons a subshell, to get a joined version of a string assigned to another variable.
As for the disadvantages: you would have to be careful at passing a correct parameter name, and passing
__r
would give you__r[@]
. The behavior of variable indirection to also expand other forms of parameters is also not explicitly documented.This works from 3.1 to 5.0-alpha. As observed, variable indirection doesn't only work with variables, but other parameters as well.
Arrays and array elements are also parameters (entities that store value), and references to arrays are technically references to parameters as well. And much like the special parameter
@
,array[@]
also makes a valid reference.Altered or selective forms of expansion (like substring expansion) that deviate reference from the parameter itself no longer work.
I would echo the array as a string, then transform the spaces into line feeds, and then use
paste
to join everything in one line like so:tr " " "\n" <<< "$FOO" | paste -sd , -
Results:
a,b,c
This seems to be the quickest and cleanest to me !
Maybe, e.g.,