Skip to content

Instantly share code, notes, and snippets.

@JeyDi
Forked from mihow/load_dotenv.sh
Created January 15, 2024 08:48
Show Gist options
  • Save JeyDi/026b34ddcf292953469e7ceca65052f1 to your computer and use it in GitHub Desktop.
Save JeyDi/026b34ddcf292953469e7ceca65052f1 to your computer and use it in GitHub Desktop.
Load environment variables from dotenv / .env file in Bash
if [ ! -f .env ]
then
export $(cat .env | xargs)
fi
@JeyDi
Copy link
Author

JeyDi commented Jan 15, 2024

Update

VSCode Python extension automatically loads the .env file in your project folder.

Better to use something like that
[ ! -f .env ] || export $(grep -v '^#' .env | xargs)

Or you can also use without xargs that it's easy: export "$(grep -vE "^(#.*|\s*)$" .env)"

Sometime this expression ca cause problems when you have complex stuff, so it's better to use a more complex regexp

source <(cat development.env | sed -e '/^#/d;/^\s*$/d' -e "s/'/'\\\''/g" -e "s/=\(.*\)/='\1'/g")

In Python, you can also use do: print(sorted(os.environ.items())) to print the variables.

A possible function implementation for this:

loadEnv() {
  local envFile="${1?Missing environment file}"
  local environmentAsArray variableDeclaration
  mapfile environmentAsArray < <(
    grep --invert-match '^#' "${envFile}" \
      | grep --invert-match '^\s*$'
  ) # Uses grep to remove commented and blank lines
  for variableDeclaration in "${environmentAsArray[@]}"; do
    export "${variableDeclaration//[$'\r\n']}" # The substitution removes the line breaks
  done
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment