shell

How to set environment variables from .env file


Let's say I have .env file contains lines like below:

USERNAME=ABC
PASSWORD=PASS

Unlike the normal ones have export prefix so I cannot source the file directly.

What's the easiest way to create a shell script that loads content from .env file and set them as environment variables?


Solution

  • 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