This is where the "${arr[*]}"
expansion form is useful (note the double quotes and the *
index). This joins the array elements using the first character of the IFS
variable
arr=(a b c d e)
joined=$(IFS='-'; echo "${arr[*]}")
declare -p joined
# => declare -- joined="a-b-c-d-e"
But if you want all-but-the-last elements, you'll combine this with the ${var:offset:length}
expansion
joined=$(IFS='-'; echo "${arr[*]:0: ${#arr[@]} - 1}")
declare -p joined
# => declare -- joined="a-b-c-d"
This one's a little tricker. The offset
and length
parts of that expansion are arithmetic expressions. I'm calculating the length as "the number of elements in the array minus one".
Note how I'm defining IFS
inside the command substitution parentheses: this is overriding the variable in the subshell of the command substitution, so it won't affect the IFS variable in your current shell.