How can I join elements of an array in Bash?

前端 未结 30 2162
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 12:05

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.

30条回答
  •  情话喂你
    2020-11-22 12:10

    Perhaps I'm missing something obvious, since I'm a newb to the whole bash/zsh thing, but it looks to me like you don't need to use printf at all. Nor does it get really ugly to do without.

    join() {
      separator=$1
      arr=$*
      arr=${arr:2} # throw away separator and following space
      arr=${arr// /$separator}
    }
    

    At least, it has worked for me thus far without issue.

    For instance, join \| *.sh, which, let's say I'm in my ~ directory, outputs utilities.sh|play.sh|foobar.sh. Good enough for me.

    EDIT: This is basically Nil Geisweiller's answer, but generalized into a function.

提交回复
热议问题