Set Environment Variables in Your Bash Shell From a .env File (Version 2)

Published: Jan 14, 2021 • Updated: Jan 14, 2022

This post is version 2 of Set Environment Variables in Your Bash Shell From a Env File.

The advantage is it supports quoted values that contain spaces.

.env file #

# Some comment
FULL_NAME="First Middle Last"
FOO=bar

setenv.sh script #

#!/usr/bin/env bash

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

# Export env vars
set -o allexport
source .env
set +o allexport

Usage #

  1. Unset env vars

     unset FULL_NAME
     unset FOO
    
  2. Set env vars in your Bash shell

     source setenv.sh
    
  3. Confirm env vars

     echo ${FULL_NAME}
     echo ${FOO}