Export environment variables from dotenv (.env) files

(, en)

To export everything in your .env file, you can run

export $(<.env grep -v "^#" | xargs)

Inside a bash script you could use:

load_dotenv() {
  set -o allexport
  # shellcheck disable=SC1091
  [[ -f .env ]] && source .env
  # default variable that should be exported if not set earlier
  : "${ENV:=dev}"
  set +o allexport

see also discussion on github

If you have a more complex setup, e.g. JSON blobs stored in environment variables


you might have to fall back to a more sophisticated solution. Here is a small python script (fmt-env) I use to format the .env file:

#!/usr/bin/env python3
import sys
import shlex
import re

def quote(line):
    k, v = line.strip().split("=", 1)
    return "{}={}".format(k, shlex.quote(v))

stmts = [quote(x) for x in sys.stdin if not re.match(r"\s*(#|$)", x)]

Call the script via

export $(<.env fmt-env | xargs)

(Do not forget to chmod +x fmt-env before you use it)

In case you have to get your .env setup into JSON format (for e.g. cypress), you can use

node \
  -e "require('dotenv').config(); process.stdout.write(JSON.stringify(process.env, null, 2))" \

(this assumes that you have the dotenv-package installed.)