Export env variables from file in a makefile

environment-variablesmake

I'm trying to write a make task that will export all variables from my
.env file, which should look like this:

A=1
B=2

If I type in terminal:

set -a
. ./.env
set +a

it works perfectly.

But same task in Makefile doesn't work:

export.env:
    set -a
    . ./.env
    set +a


make export.env # done
printenv | grep A # nothing!

I need these vars to persist after make task finished.

Best Answer

Like any process, make can’t modify the environment of an existing process, it can only control the environment which is passed to processes it starts. So short of stuffing the input buffer, there’s no way to do what you’re trying to do.

In addition, make processes each command line in a different shell, so your set -a, . ./.env, and set +a lines are run in separate shells. The effects of . ./.env will only be seen in the shell which runs that command.

Related Question