Last active
December 27, 2022 20:12
-
-
Save mtik00/de519da5ef95920deb2acd4c3ec36330 to your computer and use it in GitHub Desktop.
Joining an array in Bash (like " ".join() in Python)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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