Get .env file variables into bash scripts

If your server has a .env file, it may be necessary to parse those variables into a bash script. This can be accomplished by using the ‘source’ command.

A .env file is an important part of any application set up because it allows you to separate credentials of the app into different environments and pulls them out of the git repository.

Contents of a .env file may look like this:
DB_USERNAME=root
DB_PASSWORD=S0S3CUR3!

How to pull .env variables into a bash script:

Make sure to start with the right shebang at the top of your file.

#!/bin/bash

Pull in .env variables

source ~/.env

Then reference those variables in your script

echo “$DB_USERNAME”