How can I join elements of an array in Bash?

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

    Use perl for multicharacter separators:

    function join {
       perl -e '$s = shift @ARGV; print join($s, @ARGV);' "$@"; 
    }
    
    join ', ' a b c # a, b, c
    

    Or in one line:

    perl -le 'print join(shift, @ARGV);' ', ' 1 2 3
    1, 2, 3
    

提交回复
热议问题