Skip to content

Instantly share code, notes, and snippets.

@mihow
Last active September 23, 2023 14:55
Star You must be signed in to star a gist
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
@khoahuynhdev
Copy link

env $(cat .env)
this does not work for me but this one works

env $(cat .env|xargs) CMD

my .env has some special value such as FOO='VPTO&wH7$^3ZHZX$o$udY4&i'
@NatoBoram

@simonrouse9461
Copy link

A simple solution that works for bash, zsh, and fish:

eval export $(cat .env)

@lalten
Copy link

lalten commented Jul 11, 2023

Use this to create the file

export -p > .env

and just

. .env

to read it back in

From man export:

The shell shall format the output, including the proper use of quoting, so that it is suitable for reinput to the shell as commands that achieve the same exporting results

@ddosia
Copy link

ddosia commented Aug 2, 2023

Although set -a; source .env; set +a is elegant and short, one feature which I missed is this overwrite existing exported variables.
I my use case I have a script, which connects to postgres with a predefined user. This user is stored in .env file as PG_USER=myuser. So the script does the magical set -a; source .env; set +a and everything works. But sometimes I need ad-hoc change the user. So what I'd do is PG_USER=postgres ./my_script.sh. In order not to over write the existing var I did this horrendous piece of code:

IFS=$'\n'
for l in $(cat /etc/my_service/.env); do
    IFS='=' read -ra VARVAL <<< "$l"
    # If variable with such name already exists, preserves it's value
    eval "export ${VARVAL[0]}=\${${VARVAL[0]}:-${VARVAL[1]}}"
done
unset IFS

@dangvanduc90
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

work like a charm. ty

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