Skip to content

Instantly share code, notes, and snippets.

@mtik00
Last active December 27, 2022 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtik00/de519da5ef95920deb2acd4c3ec36330 to your computer and use it in GitHub Desktop.
Save mtik00/de519da5ef95920deb2acd4c3ec36330 to your computer and use it in GitHub Desktop.
Joining an array in Bash (like " ".join() in Python)
function array_join() {
# Join an array with a a separator character.
# WARNING: This only works in bash. You should also pass the array by
# reference. Example:
# my_array=( "one" "two" "three")
# joined=$( array_join my_array "|")
local -n arr=$1
local sep=${2:-" "}
printf -v result "%s${sep}" "${arr[@]}"
# strip the last separator character
printf "%s" "${result%?}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment