Join an array to a string
Join array values with a separator, optionally using a different separator before the last item.
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.