Skip to content

Instantly share code, notes, and snippets.

@nuxlli
Last active February 1, 2024 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nuxlli/994e42de0be612e9ba76fb6dcc815103 to your computer and use it in GitHub Desktop.
Save nuxlli/994e42de0be612e9ba76fb6dcc815103 to your computer and use it in GitHub Desktop.
Loading dotenv files with exports and interpolations without override the current vars
#!/usr/bin/env bash
# This function loads variables from a .env (dotenv format) files without
# override the current variables. It will fix the relative paths.
#
# Example:
#
# $ export ENV=developer
# $ cat dotenvs/.env
# ENV=staging
# ENV_UP="${ENV^^}"
# export ENV_NAME=${ENV}
# ENV_PATH="../"
#
# $ loadDotenvFile ./.env true
# $ env | grep ENV
# ENV=staging
# ENV_NAME=staging
# ENV_UP="STAGING"
# ENV_PATH="./"
#
loadDotenvFile() {
if [ -d "${1}" ]; then
log "Path ${1} exist, but is a directory"
elif [ -f "${1}" ]; then
envfile="${1}"
# https://regexr.com/4dnme
# https://stackoverflow.com/a/2821201/469463
log "Load envs from ${envfile}"
content="$(sed -E 's/^(export[[:space:]]*)?([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})={1}(.*)$/export \2=\${\2:-\3}/g' "${envfile}")"
eval "${content}"
fixpath="${2:-false}"
if [[ "$fixpath" == "true" ]]; then
# Fix relative values
folder="$(dirname "${envfile}")"
parent="$(dirname "${folder}")"
vars=()
while IFS='' read -r line; do vars+=("$line"); done < <(printenv | grep '=\.\.\?\/')
for var in "${vars[@]}"; do
eval "export $(echo "$var" | sed -E 's|^(.*=)\.(\/.*)|\1'"${folder}"'\2|g')"
eval "export $(echo "$var" | sed -E 's|^(.*=)\.\.(\/.*)|\1'"${parent}"'\2|g')"
done
fi
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment