Set Environment Variables in Your Bash Shell From a .env File
Published: Jul 28, 2020
Updated: May 3, 2021
Updated: May 3, 2021
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.
Also see Version 2 of this post.
.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 #
-
Set env vars in your Bash shell
source setenv.sh
-
Confirm env vars
echo "${FIRST_NAME} ${LAST_NAME}"