How to set environment variables from .env file

If your lines are valid, trusted shell but for the export command

This requires appropriate shell quoting. It’s thus appropriate if you would have a line like foo='bar baz', but not if that same line would be written foo=bar baz

set -a # automatically export all variables
source .env
set +a

If your lines are not valid shell

The below reads key/value pairs, and does not expect or honor shell quoting.

while IFS== read -r key value; do
  printf -v "$key" %s "$value" && export "$key"
done <.env

Leave a Comment