Skip to main content

Set Environment Variables in your Bash shell from a .env file

Published: 2020-07-28

I experimented with many ways of doing this, but my favorite solution was from this stackoverflow answer. It keeps the .env file syntax clean so that it can be used across projects. Here’s a minimal, reproducible example.

.env file #

# Some comment
FIRST_NAME=Agnes
LAST_NAME=Obel

setenv.sh script #

#!/usr/bin/env bash

# Show env vars
grep -v '^#' .env

# Export env vars
export $(grep -v '^#' .env | xargs)

Usage #

  1. Set env vars in your Bash shell

     source ./setenv.sh
    
  2. Confirm env vars

     echo "${FIRST_NAME} ${LAST_NAME}"