Makefile include env file

If you are using gnu make, what should work is to include the envfile file, then export the list of vars got from the same file:

#!make
include envfile
export $(shell sed 's/=.*//' envfile)

test:
        env

I had a similar problem and landed on this thread. Another possible solution is to just do the make export command without any arguments:

include .env
export

This will export all make variables as environment variables. This behavior may or may not match all use cases, but it worked for me and didn't involve any shell scripting wizardry.


Preserves pre existing ENV vars

export $(shell [ ! -n "$(ENVFILE)" ] || cat $(ENVFILE) | grep -v \
    --perl-regexp '^('$$(env | sed 's/=.*//'g | tr '\n' '|')')\=')

test:
    echo $$FOO

To run

make ENVFILE=envfile test # bar

export FOO=foo
make ENVFILE=envfile test # foo