How can I join elements of an array in Bash?

前端 未结 30 2453
爱一瞬间的悲伤
爱一瞬间的悲伤 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

    With re-use of @doesn't matters' solution, but with a one statement by avoiding the ${:1} substition and need of an intermediary variable.

    echo $(printf "%s," "${LIST[@]}" | cut -d "," -f 1-${#LIST[@]} )
    

    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.

提交回复
热议问题