Last active
February 21, 2024 04:02
-
-
Save kriansa/59d7e2e0b302b971588c19eff63c7f28 to your computer and use it in GitHub Desktop.
Pure bash dotenv
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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