How can I join elements of an array in Bash?

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

    Here's one that most POSIX compatible shells support:

    join_by() {
        # Usage:  join_by "||" a b c d
        local arg arr=() sep="$1"
        shift
        for arg in "$@"; do
            if [ 0 -lt "${#arr[@]}" ]; then
                arr+=("${sep}")
            fi
            arr+=("${arg}") || break
        done
        printf "%s" "${arr[@]}"
    }
    

提交回复
热议问题