tags:

views:

1010

answers:

5

If I've got an array like this in Bash:

FOO=( a b c )

How do I join the elements with commas? For example, producing a,b,c.

+8  A: 

Maybe, e.g.,

SAVE_IFS=$IFS
IFS=","
FOOJOIN="${FOO[*]}"
IFS=$SAVE_IFS

echo $FOOJOIN
martin clayton
Hrm… For some reason, my IFS doesn't want to change:$ IFS=","; $ echo -$IFS- ==> - -
David Wolever
If you do that, it thinks that IFS- is the variable. You have to do `echo "-${IFS}-"` (the curly braces separate the dashes from the variable name).
Dennis Williamson
Still got the same result (I just put the dashes in to illustrate the point… `echo $IFS` does the same thing.
David Wolever
That said, this still seems to work… So, like most things with Bash, I'll pretend like I understand it and get on with my life.
David Wolever
A "-" is not a valid character for a variable name, so the shell does the right thing when you use $IFS-, you don't need ${IFS}- (bash, ksh, sh and zsh in linux and solaris also agree).
Idelic
@David the difference between your echo and Dennis's is that he has used double quoting. The content of IFS is used 'on input' as a declaration of word-separator characters - so you'll always get an empty line without quotes.
martin clayton
A: 

Right now I'm using:

TO_IGNORE=(
    E201 # Whitespace after '('
    E301 # Expected N blank lines, found M
    E303 # Too many blank lines (pep8 gets confused by comments)
)
ARGS="--ignore `echo ${TO_IGNORE[@]} | tr ' ' ','`"

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)

David Wolever
from where do you get those array values? if you are hardcoding it like that, why not just foo="a,b,c".?
ghostdog74
In this case I actually *am* hard-coding the values, but I want to put them in an array so I can comment on each individually. I've updated the answer to show you what I mean.
David Wolever
+1  A: 

This approach takes care of spaces within the values, but requires a loop:

#!/bin/bash

FOO=( a b c )
BAR=""

for index in ${!FOO[*]}
do
    BAR="$BAR,${FOO[$index]}"
done
echo ${BAR:1}
dengel
+2  A: 

Yet another solution:

#/!bin/bash
foo=('foo bar' 'foo baz' 'bar baz')
bar=$(printf ",%s" "${foo[@]}")
bar=${bar:1}

echo $bar
doesn't matters
A: 
a=(a b c)
b=(d e f)
a=(`echo ${a[*]} ${b[*]}`)
echo ${a[*]}
a b c d e f
wolfay