Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Load environment variables from dotenv / .env file in Bash
if [ ! -f .env ]
then
export $(cat .env | xargs)
fi
@tolmanam

This comment has been minimized.

Copy link

tolmanam commented Sep 14, 2018

FWIW - I found this helpful, but it didn't do what I had expected. Modified it slightly to result in the following.

if [ -f .env ]
then
  export $(cat .env | sed 's/#.*//g' | xargs)
fi
@rjchicago

This comment has been minimized.

Copy link

rjchicago commented Oct 2, 2018

The above worked fine for me, but thought I'd share the solution I went with:
https://stackoverflow.com/a/30969768/179329
set -o allexport; source .env; set +o allexport

@marcelovani

This comment has been minimized.

Copy link

marcelovani commented Apr 3, 2019

I like this

@hsundara

This comment has been minimized.

Copy link

hsundara commented Aug 13, 2019

FWIW - I found this helpful, but it didn't do what I had expected. Modified it slightly to result in the following.

if [ -f .env ]
then
  export $(cat .env | sed 's/#.*//g' | xargs)
fi

You have won an award!

@alex-ross

This comment has been minimized.

Copy link

alex-ross commented Mar 24, 2020

I use this

envup() {
  local file=$([ -z "$1" ] && echo ".env" || echo ".env.$1")

  if [ -f $file ]; then
    set -a
    source $file
    set +a
  else
    echo "No $file file found" 1>&2
    return 1
  fi
}

It allows me to run envup to load the .env file or envup custom to load .env.custom.

@valmayaki

This comment has been minimized.

Copy link

valmayaki commented Apr 24, 2020

Here is a modified version of this code that allows for variable expansion

if [ -f .env ]; then
  export $(echo $(cat .env | sed 's/#.*//g'| xargs) | envsubst)
fi
@sebaxtian

This comment has been minimized.

Copy link

sebaxtian commented May 5, 2020

Hi everyone, this works for me:

.env file

# Environment Variables
KAGGLE_USERNAME=sebaxtian
KAGGLE_KEY=example_kaggle_key
# Local .env
if [ -f .env ]; then
    # Load Environment Variables
    export $(cat .env | grep -v '#' | awk '/=/ {print $1}')
    # For instance, will be example_kaggle_key
    echo $KAGGLE_KEY
fi
@mortymacs

This comment has been minimized.

Copy link

mortymacs commented May 19, 2020

export $(grep -v '^#' .env | xargs)
@mortymacs

This comment has been minimized.

Copy link

mortymacs commented May 19, 2020

Thank you so much for the solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.