Loading .env (dotenv) using bash or zsh

Keep Cloud Native and follow 12 Factor Apps with dotenv even in Shell Bash Zsh scripts

Loading .env (dotenv) using bash or zsh

The dotenv approach has been around quite some time with tremendous support in tooling, frameworks, etc. I'm not sure if this started in nodejs but it's available across many languages now. Tooling like Visual Studio Code support the .env files - see Environment Variables. The use of environment variables is also one of the factors in The Twelve Factor App - Config.

In one area I've seen different approaches, but similar to the following:

if [ ! -f .env ]
then
  export $(cat .env | xargs)
fi

However, something that I find far simpler is to use the allexport feature of bash/zsh

set -o allexport; source .env; set +o allexport

Can also be shortened to: (see All Export Built in):

set -a; source .env; set +a