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
.
Rewriting solution by Pascal Pilz as a function in 100% pure Bash (no external commands):
For example,
Alternatively, we can use printf to support multi-character delimiters, using the idea by @gniourf_gniourf
For example,
With re-use of @doesn't matters' solution, but with a one statement by avoiding the ${:1} substition and need of an intermediary variable.
printf has 'The format string is reused as often as necessary to satisfy the arguments.' in its man pages, so that the concatenations of the strings is documented. Then the trick is to use the LIST length to chop the last sperator, since cut will retain only the lenght of LIST as fields count.
Using no external commands:
Warning, it assumes elements don't have whitespaces.
Surprisingly my solution is not yet given :) This is the simplest way for me. It doesn't need a function:
Note: This solution was observed to work well in non-POSIX mode. In POSIX mode, the elements are still joined properly, but
IFS=,
becomes permanent.Right now I'm using:
Which works, but (in the general case) will break horribly if array elements have a space in them.
(For those interested, this is a wrapper script around pep8.py)