8

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.

whitered
  • 191

2 Answers2

9

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.

Stephen Kitt
  • 434,908
  • Unfortunately, your answer does not help the person who send the question. See my answer for a hint on how to do it. – schily Jun 15 '18 at 08:29
  • 2
    @schily I don’t see how your answer helps, given that the OP said “I need these vars to persist after make task finished.” – Stephen Kitt Jun 15 '18 at 08:34
  • OK, 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. – schily Jun 15 '18 at 08:37
6

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.

schily
  • 19,173
  • 2
    Not sure why you were downvoted but adding -include /path/to/.env to Makefile works well for me. – Nav Jun 07 '20 at 22:44