Skip to content

Instantly share code, notes, and snippets.

Last active February 3, 2023 09:21
What would you like to do?
Load environment variables from dotenv / .env file in Bash
if [ ! -f .env ]
export $(cat .env | xargs)
Copy link

The above worked fine for me, but thought I'd share the solution I went with:

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

Copy link

miedza commented Sep 29, 2022

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

Copy link

bergpb commented Dec 9, 2022

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

Sweet, works like a charm for me, thanks.

Copy link

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

thank you this was better

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)

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