Skip to content

Join an Array to a String

Join nameref array values with a separator, and optionally use a different separator before the last item for natural-language lists.

Language: Shell

Added on: 18th August 2026

array_to_string() {
  separator="$1"
  local -n arr=$2

  regex="$( printf "${separator}%s" "${arr[@]}" )"
  regex="${regex:${#separator}}"

  if [[ -n $3 ]]; then
    if [[ $regex = *"$separator"* ]]; then
      prefix=${regex%"$separator"*}
      suffix=${regex#"$prefix"}
      regex=${prefix}${suffix/"$separator"/"$3"}
    fi
  fi

  echo "${regex}"
}

Caveats

Needs Bash namerefs (Bash 4.3+). Pass the array name as the second argument.