Skip to content

Instantly share code, notes, and snippets.

@jamesthomasonjr
Created February 21, 2020 16:32
Show Gist options
  • Save jamesthomasonjr/96b2b233ee58816e204c587733119fc3 to your computer and use it in GitHub Desktop.
Save jamesthomasonjr/96b2b233ee58816e204c587733119fc3 to your computer and use it in GitHub Desktop.
bash utilities
#!/usr/bin/env bash
# Utility functions for dealing with the environment
source "$(dirname ${BASH_SOURCE[0]})/sanity"
function environment::read {
# @TODO: Check for original allexport setting and return back instead of assuming it's off
set -o allexport
for envfile in "$@"; do
if [ -s "${envfile}" ]; then
source "${envfile}"
fi
done
set +o allexport
}
function environment::export {
# This function requires an even number of arguments
sanity::even_arguments "$@"
# Loop through key/value pairs, setting key to value if it doesn't already exist
while [[ $# -gt 0 ]]; do
local key="$1"; shift
local default="$1"; shift
if [ -z "${!key+x}" ]; then
export $key="${default}"
fi
done
}
function environment::export_with_file_default {
# This function requires an even number of arguments
sanity::even_arguments "$@"
while [[ $# -gt 0 ]]; do
local key="$1"; shift
local filename="$1"; shift
# Only set variable if not already set and the file exists
if [ -s "${filename}" ] && [ -z "${!key+x}" ]; then
export $key="${filename}"
fi
done
}
#!/usr/bin/env bash
# Utility functions for sanity checks
function sanity::even_arguments {
if [ $(($#%2)) -ne 0 ]; then
echo "Odd number of arguments provided to ${FUNCNAME[1]}! An even number is required."
exit 1
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment