Skip to content

Instantly share code, notes, and snippets.

@mihow
Last active September 16, 2024 17:00
Show Gist options
  • Save mihow/9c7f559807069a03e302605691f85572 to your computer and use it in GitHub Desktop.
Save mihow/9c7f559807069a03e302605691f85572 to your computer and use it in GitHub Desktop.
Load environment variables from dotenv / .env file in Bash
# The initial version
if [ ! -f .env ]
then
export $(cat .env | xargs)
fi
# My favorite from the comments. Thanks @richarddewit & others!
set -a && source .env && set +a
@lsotoj
Copy link

lsotoj commented Sep 21, 2021

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

Thanks so much. I love it.

@aslamanver
Copy link

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

Hats off man

@xmarkclx
Copy link

xmarkclx commented Oct 7, 2021

Doesn't work for me because of JWT in the .env with lots of newlines.
Had to manually vim copy paste the contents instead.

@nickbien
Copy link

this worked for me, from @rjchicago snippet
set -o allexport; source .env; set +o allexport

@geekwhocodes
Copy link

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

worked like a charm. Thanks!

@NatoBoram
Copy link

FWIW If you need to just run a command with environment from an env file, this could help:

env $(cat .env|xargs) CMD

provided there are no other lines except env definitions in form of VAR=VALUE. Don't remember where I found it, but does the trick for me.

You can actually get away without xargs

env $(cat .env) <command>

@fzancan-SpazioCodice
Copy link

export $( grep -vE "^(#.*|\s*)$" .env )

@J5Dev
Copy link

J5Dev commented Nov 8, 2021

The cleanest solution I found for this was using allexport and source like this

set -o allexport
source .env set
+o allexport

This was by far the best solution here for me, removed all the complexity around certain chars, spaces comments etc. Just needed a tweak on formatting to prevent others being tripped up, should be:

set -o allexport
source .env
set +o allexport

@MrYutz
Copy link

MrYutz commented Nov 11, 2021

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

I like this too.

@n1k0
Copy link

n1k0 commented Mar 1, 2022

oh-my-zsh users can also activate the dotenv plugin.

@BinitaBharati
Copy link

source .env

works for me

wont work if you have # in your .env

Thanks for this.

@xswirelab
Copy link

@devzom
Copy link

devzom commented Mar 16, 2022

Great work ! :)

  • I have .env with [VAR1=xyz, VAR2=233, NPM_TOKEN=123]

  • Seems that this example from @valmayaki :

if [ -f .env ]; then
  export $(echo $(cat .env | sed 's/#.*//g'| xargs) | envsubst)
fi
# always response as one liner with all the variables
  • I switched to use this without xargs:
export "$(grep -vE "^(#.*|\s*)$" .env)"
# as it's responding with single value ex: 
echo $NPM_TOKEN # just print the single variable

thanks to all for great cooperation <3

@michchan
Copy link

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

This works!

@alphanetEX
Copy link

The cleanest solution I found for this was using allexport and source like this

set -o allexport
source .env set
+o allexport

This was by far the best solution here for me, removed all the complexity around certain chars, spaces comments etc. Just needed a tweak on formatting to prevent others being tripped up, should be:

set -o allexport source .env set +o allexport

Many thanks for this solution reference

@theofanisv
Copy link

That 's great, thanks

@wffranco
Copy link

wffranco commented Jun 29, 2022

@chengxuncc

using export $(grep -v '^#' .env | xargs) could not export the following,

A=10
B=$A
C=${A}

now, echo $B produces $A while it should print 10

this read line by line, allowing to use previous set variables

  while read -r LINE; do
    if [[ $LINE == *'='* ]] && [[ $LINE != '#'* ]]; then
      ENV_VAR="$(echo $LINE | envsubst)"
      eval "declare $ENV_VAR"
    fi
  done < .env

@Krong1997
Copy link

@wffranco

@chengxuncc
using export $(grep -v '^#' .env | xargs) could not export the following,

A=10
B=$A
C=${A}

now, echo $B produces $A while it should print 10

this read line by line, allowing to use previous set variables

  while read -r LINE; do
    if [[ $LINE == *'='* ]] && [[ $LINE != '#'* ]]; then
      ENV_VAR="$(echo $LINE | envsubst)"
      eval "declare $ENV_VAR"
    fi
  done < .env

This solution is helpful!
Thanks a lot!

@bergkvist
Copy link

bergkvist commented Jul 26, 2022

You can also do:

eval "$(
  cat .env | awk '!/^\s*#/' | awk '!/^\s*$/' | while IFS='' read -r line; do
    key=$(echo "$line" | cut -d '=' -f 1)
    value=$(echo "$line" | cut -d '=' -f 2-)
    echo "export $key=\"$value\""
  done
)"

This ignores empty lines, and lines starting with # (comments). If you replace eval with echo - you can inspect the generated code.

@richarddewit
Copy link

The cleanest solution I found for this was using allexport and source like this

set -o allexport
source .env set
+o allexport

This was by far the best solution here for me, removed all the complexity around certain chars, spaces comments etc. Just needed a tweak on formatting to prevent others being tripped up, should be:

set -o allexport
source .env
set +o allexport

From man set:

       -o option
             This  option  is  supported if the system supports the User Portability Utilities op‐
             tion. It shall set various options, many of which shall be equivalent to  the  single
             option letters. The following values of option shall be supported:

             allexport Equivalent to -a.

So this is the same as

set -a            
source .env
set +a

@jairajsahgal
Copy link

[ ! -f .env ] || export $(sed 's/#.*//g' .env | xargs)

Update: TEXT="abc#def" not work as expected, so just replace line begin with #.

[ ! -f .env ] || export $(grep -v '^#' .env | xargs)

This one works for django .env

@SrEnrique
Copy link

this works for me

#!/usr/bin/env bash
. .env

@drjasonharrison
Copy link

For those using sed to rewrite their .env files before evaluation by bash, for example the solution suggested by @kolypto in https://gist.github.com/mihow/9c7f559807069a03e302605691f85572?permalink_comment_id=3625310#gistcomment-3625310

I ran into another case that hadn't been considered: Windows line endings "\r\n". I'm now using:

    set -o allexport # enable all variable definitions to be exported
    source <(sed -e "s/\r//" -e '/^#/d;/^\s*$/d' -e "s/'/'\\\''/g" -e "s/=\(.*\)/=\"\1\"/g" "${ENV_FILE}")
    set +o allexport

@bolorundurovj
Copy link

The cleanest solution I found for this was using allexport and source like this

set -o allexport
source .env set
+o allexport

This was by far the best solution here for me, removed all the complexity around certain chars, spaces comments etc. Just needed a tweak on formatting to prevent others being tripped up, should be:
set -o allexport
source .env
set +o allexport

From man set:

       -o option
             This  option  is  supported if the system supports the User Portability Utilities op‐
             tion. It shall set various options, many of which shall be equivalent to  the  single
             option letters. The following values of option shall be supported:

             allexport Equivalent to -a.

So this is the same as

set -a            
source .env
set +a

Worked for me

@rjchicago
Copy link

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

As @richarddewit pointed out above, -a/+a can be used in place of -o allexport to be more concise (thanks!).

I now use the following simple line to source .env files into my scripts...

set -a; source .env; set +a

@miedza
Copy link

miedza commented Sep 29, 2022

export $(awk -F= '{output=output" "$1"="$2} END {print output}' aaa.env)

@bergpb
Copy link

bergpb commented Dec 9, 2022

[ ! -f .env ] || export $(grep -v '^#' .env | xargs)

Sweet, works like a charm for me, thanks.

@bruteforks
Copy link

oh-my-zsh users can also activate the dotenv plugin.

thank you this was better

@C-Duv
Copy link

C-Duv commented Jan 20, 2023

I had troubles with a (Docker) setup where environment variables had spaces in their value without quotes and I needed to get the container's env. vars. in a script called during the container execution/runtime.

I ended getting the variables in the entrypoint, exporting them to a file and them reading them when needed.

# In entrypoint
export -pn \
    | grep "=" \
    | grep -v -e PATH -e PWD -e OLDPWD \
    | cut -d ' ' -f 3- \
    > /docker-container.env

The export command fixes issues with missing quotes, avoiding errors where the shell interpreter tries to execute parts of the variable value as commands.

# In script
set -o allexport
. /docker-container.env
set +o allexport

(I had to use /bin/sh so not using source file but . file)

@usmanhalalit
Copy link

oh-my-zsh users can also activate the dotenv plugin.

Fantastic! Thanks @n1k0!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment