Skip to content

Instantly share code, notes, and snippets.

@rico-chet
Last active September 13, 2018 23:54
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 rico-chet/0229e4c080d9f51a02535dd25a656a8a to your computer and use it in GitHub Desktop.
Save rico-chet/0229e4c080d9f51a02535dd25a656a8a to your computer and use it in GitHub Desktop.
Bash function `join` that joins a number of elements to a colon-separated variable, gracefully appending to an existing one when present.
#!/usr/bin/env bash
##
## Copyright (C) 2018 Alex Thiessen <alex.thiessen.de+github@gmail.com>
## Copyright (C) 2018 https://unix.stackexchange.com/users/116858/kusalananda
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 2 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
## FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, write to the Free Software Foundation, Inc., 51
## Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
##
## SPDX-License-Identifier: GPL-2.0-or-later
## <https://spdx.org/licenses/GPL-2.0-or-later.html>
##
set -o nounset
set -o errexit
function join() {
if [ ${#} -eq 0 ]
then
echo "\`join\` appends elements separated by colons to a \`bash\` variable " >&2
echo "usage: join <variable> <element> [element ...]" >&2
return 1
fi
variable="${1}"
shift
export ${variable}="${!variable:+${!variable}:}$(IFS=:; echo "${*}")"
}
# ensure that this fails
if join
then
return 1
fi
export foo=X
join foo Y
[ "$foo" = "X:Y" ]
export foo=
join foo Y
[ "$foo" = "Y" ]
unset foo
join foo Y
[ "$foo" = "Y" ]
export foo="a b"
join foo Y
[ "$foo" = "a b:Y" ]
export foo="a b"
join foo "c d"
[ "$foo" = "a b:c d" ]
export foo="a b"
join foo "c d" "e f"
[ "$foo" = "a b:c d:e f" ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment