Skip to content

Instantly share code, notes, and snippets.

@htekgulds
Created January 13, 2020 19:46
Show Gist options
  • Save htekgulds/47cf6ef86cb8b0c4d53859ba529b8f8f to your computer and use it in GitHub Desktop.
Save htekgulds/47cf6ef86cb8b0c4d53859ba529b8f8f to your computer and use it in GitHub Desktop.
file env (docker secret to environment)
# usage: file_env VAR [DEFAULT]
# ie: file_env 'XYZ_DB_PASSWORD' 'example'
# (will allow for "$XYZ_DB_PASSWORD_FILE" to fill in the value of
# "$XYZ_DB_PASSWORD" from a file, especially for Docker's secrets feature)
file_env() {
local var="$1"
local fileVar="${var}_FILE"
local def="${2:-}"
echo 'var: ' $var
echo 'fileVar: ' $fileVar
echo 'def: ' $def
if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then
echo >&2 "error: both $var and $fileVar are set (but are exclusive)"
exit 1
fi
local val="$def"
if [ "${!var:-}" ]; then
val="${!var}"
elif [ "${!fileVar:-}" ]; then
val="$(< "${!fileVar}")"
fi
export "$var"="$val"
unset "$fileVar"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment