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
.
This approach takes care of spaces within the values, but requires a loop:
Use perl for multicharacter separators:
Or in one line:
Here's a 100% pure Bash function that does the job:
Look:
This preserves even the trailing newlines, and doesn't need a subshell to get the result of the function. If you don't like the
printf -v
(why wouldn't you like it?) and passing a variable name, you can of course use a global variable for the returned string:In case the elements you want to join is not an array just a space separated string, you can do something like this:
for example, my use case is that some strings are passed in my shell script and I need to use this to run on a SQL query:
In my_script, I need to do "SELECT * FROM table WHERE name IN ('aa','bb','cc','dd'). Then above command will be useful.
This isn't all too different from existing solutions, but it avoids using a separate function, doesn't modify
IFS
in the parent shell and is all in a single line:resulting in