export env variables from file in a makefile

17,120

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.

Share:
17,120

Related videos on Youtube

Admin
Author by

Admin

Updated on September 18, 2022

Comments

  • Admin
    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
    schily about 6 years
    Unfortunately, your answer does not help the person who send the question. See my answer for a hint on how to do it.
  • schily
    schily about 6 years
    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.
  • Nav
    Nav about 4 years
    Not sure why you were downvoted but adding -include /path/to/.env to Makefile works well for me.