How can I join elements of an array in Bash?

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

    Thanks @gniourf_gniourf for detailed comments on my combination of best worlds so far. Sorry for posting code not thoroughly designed and tested. Here is a better try.

    # join with separator
    join_ws() { local d=$1 s=$2; shift 2 && printf %s "$s${@/#/$d}"; }
    

    This beauty by conception is

    • (still) 100% pure bash ( thanks for explicitly pointing out that printf is a builtin as well. I wasn't aware about this before ... )
    • works with multi-character delimiters
    • more compact and more complete and this time carefully thought over and long-term stress-tested with random substrings from shell scripts amongst others, covering use of shell special characters or control characters or no characters in both separator and / or parameters, and edge cases, and corner cases and other quibbles like no arguments at all. That doesn't guarantee there is no more bug, but it will be a little harder challenge to find one. BTW, even the currently top voted answers and related suffer from such things like that -e bug ...

    Additional examples:

    $ join_ws '' a b c
    abc
    $ join_ws ':' {1,7}{A..C}
    1A:1B:1C:7A:7B:7C
    $ join_ws -e -e
    -e
    $ join_ws $'\033[F' $'\n\n\n'  1.  2.  3.  $'\n\n\n\n'
    3.
    2.
    1.
    $ join_ws $ 
    $
    

提交回复
热议问题