Skip to content

Instantly share code, notes, and snippets.

@kriansa
Last active February 21, 2024 04:02
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 kriansa/59d7e2e0b302b971588c19eff63c7f28 to your computer and use it in GitHub Desktop.
Save kriansa/59d7e2e0b302b971588c19eff63c7f28 to your computer and use it in GitHub Desktop.
Pure bash dotenv
# This is useful for loading a .env file and ensuring you don't override the
# environment variables already set.
#
# Usage: load-env-file filename.env
load-env-file() {
local env_file=$1
# Save a reference of all existing variables
while IFS= read -rd $'\0' var; do
name="${var%%=*}"
[[ "$name" =~ ^[a-zA-Z0-9_]+$ ]] || continue
local "existing_${name}"=1
done < <(env -0)
while IFS= read -rd $'\0' var; do
# We don't override the environment variables already set
name="${var%%=*}"
value="${var#*=}"
varname="existing_${name}"
test -n "${!varname}" && continue
# Then parse each value and export them individually
eval "$(printf "export %s=%q" "$name" "$value")"
done < <(env -i -- sh -c "set -ea; . \"$env_file\"; env -0 -u SHLVL -u _ -u PWD")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment