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
@msmans
Copy link

msmans commented Jul 31, 2021

One I use (bash specific) which behaves correctly in presence of calling environment override:

. <(sed -n 's/^\([^#][^=]*\)=\(.*\)$/\1=${\1:-\2}/p' .env 2>/dev/null) || true

@shlomi-viz
Copy link

shlomi-viz commented Aug 15, 2021

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

I hate bash so much...... it took me 30 minutes to understand it should be if [ -f .env ] instead of if [ ! -f .env ] 😢

@chengxuncc
Copy link

chengxuncc commented Aug 26, 2021

[ ! -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)

@ShivKJ
Copy link

ShivKJ commented Aug 30, 2021

@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

@chengxuncc
Copy link

chengxuncc commented Aug 30, 2021

@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

@ShivKJ Of course, it will equal to export A=10 B=$A C=${A} and doesn't work like shell script. Another example is /etc/environment have same behavior and don't accept variable definition.

@kolypto
Copy link

kolypto commented Sep 12, 2021

If you're wondering how to load a .env file with direnv: direnv already supports that :)

dotenv "testing.env"

Docs: https://direnv.net/man/direnv-stdlib.1.html

@jhud
Copy link

jhud commented Sep 20, 2021

The Problem

The problem with .env files is that they're like bash, but not completely.
While in bash you'd sometimes put quotes around values:

name='value ! with > special & characters'

in .env files there are no special characters, and quotes are not supported: they're part of the value. As a result, such a string has to be escaped when imported into bash.

The Solution

This version withstands every special character in values:

set -a
source <(cat development.env | sed -e '/^#/d;/^\s*$/d' -e "s/'/'\\\''/g" -e "s/=\(.*\)/='\1'/g")
set +a

Explanation:

  • -a means that every bash variable would become an environment variable
  • /^#/d removes comments (strings that start with #)
  • /^\s*$/d removes empty strings, including whitespace
  • "s/'/'\\\''/g" replaces every single quote with '\'', which is a trick sequence in bash to produce a quote :)
  • "s/=\(.*\)/='\1'/g" converts every a=b into a='b'

As a result, you are able to use special characters :)

To debug this code, replace source with cat and you'll see what this command produces.

Thank you! I have some long and unusually formatted environment variables, and this was the only solution which didn't choke on them.

@jquick
Copy link

jquick commented Sep 21, 2021

~/bin/envs

set -a
source .env
set +a
exec $@

$> envs go run .

@lsotoj
Copy link

lsotoj commented Sep 21, 2021

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

Thanks so much. I love it.

@aslamanver
Copy link

aslamanver commented Sep 24, 2021

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

nickbien commented Oct 12, 2021

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

@geekwhocodes
Copy link

geekwhocodes commented Oct 15, 2021

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

NatoBoram commented Oct 27, 2021

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

fzancan-SpazioCodice commented Oct 29, 2021

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

BinitaBharati commented Mar 3, 2022

source .env

works for me

wont work if you have # in your .env

Thanks for this.

@xswirelab
Copy link

xswirelab commented Mar 12, 2022

@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

michchan commented Mar 27, 2022

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

alphanetEX commented May 20, 2022

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

theofanisv commented Jun 17, 2022

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

Krong1997 commented Jul 7, 2022

@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

richarddewit commented Jul 28, 2022

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

jairajsahgal commented Jul 29, 2022

[ ! -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

SrEnrique commented Jul 31, 2022

this works for me

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

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