I have a script that parses a rudimentary .env file and exports its contents as environment variables, before taking further action:
set -eu
test -f .env && load_dotenv
exec ./foobar x y z "$@"
However, this results in environment variables defined in .env taking precedence over environment variables defined in the user's shell. I want the opposite behavior: I want environment variables explicitly set in the shell to take precedence over anything defined in the .env file.
Therefore I was hoping to "save" the current environment before running load_dotenv, and then "re-apply" that saved environment after running load_dotenv:
set -eu
user_env="$( env )"
test -f .env && load_dotenv
reapply_env "$user_env" # ???
exec ./foobar x y z "$@"
How do I implement reapply_env, such that it can handle arbitrary environment variables? As far as I know, any byte other than \0 is valid in an environment variable, so I want to make sure that this works for any arbitrary env var. For example, there are legitimate (although unusual) use cases for embedded newlines in environment variables.
I'm open to shell-specific answers, but assume I am using a Bourne-flavored shell (Bash, Ksh, Zsh, etc.).
Ignore security issues. Assume I am operating in a trusted, controlled environment, and that any scenario like "tricking the developer into downloading a malicious .env file" involves a broader security problem that's beyond the scope of this question.
Edit: How to avoid overwriting env vars is a great question, but it's not what I'm interested in answering in this particular question. I can post a separate one for that, if there isn't already a duplicate.