How can I join elements of an array in Bash?

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

    Combine best of all worlds so far with following idea.

    # join with separator
    join_ws()  { local IFS=; local s="${*/#/$1}"; echo "${s#"$1$1$1"}"; }
    

    This little masterpiece is

    • 100% pure bash ( parameter expansion with IFS temporarily unset, no external calls, no printf ... )
    • compact, complete and flawless ( works with single- and multi-character limiters, works with limiters containing white space, line breaks and other shell special characters, works with empty delimiter )
    • efficient ( no subshell, no array copy )
    • simple and stupid and, to a certain degree, beautiful and instructive as well

    Examples:

    $ join_ws , a b c
    a,b,c
    $ join_ws '' a b c
    abc
    $ join_ws $'\n' a b c
    a
    b
    c
    $ join_ws ' \/ ' A B C
    A \/ B \/ C
    

提交回复
热议问题