How can I join elements of an array in Bash?

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

    Using no external commands:

    $ FOO=( a b c )     # initialize the array
    $ BAR=${FOO[@]}     # create a space delimited string from array
    $ BAZ=${BAR// /,}   # use parameter expansion to substitute spaces with comma
    $ echo $BAZ
    a,b,c
    

    Warning, it assumes elements don't have whitespaces.

提交回复
热议问题