export env variables from file in a makefile
Solution 1
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.
Solution 2
Modern make
implementations include support for managing the environment.
GNU make does, my smake
does and my enhanced version of SunPro Make
that is available in the schilytools
tarball supports it.
If you carefully write your env
file to have assignments and export
statements on different lines, you can include
the env
file in your Makefile
.
Use e.g.:
include $(HOME)/.env
in your Makefile
.
Related videos on Youtube
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Admin
Updated on September 18, 2022Comments
-
Admin almost 2 years
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.
-
schily about 6 yearsUnfortunately, your answer does not help the person who send the question. See my answer for a hint on how to do it.
-
schily about 6 yearsOK, I did not see this and the header does not mention that the question was not related to the make, but asks for help with make.
-
Nav about 4 yearsNot sure why you were downvoted but adding
-include /path/to/.env
to Makefile works well for me.