Search code examples
variablesmakefileenvironment

environment variable set in make not seen by all sub-shells


I need to set env variables in a makefile and use them in a python script invoked by the makefile. For some reason the python script is not able to see these env variables.

export VAR := env_var
PY_VAR := python -c "import os; print('VAR=' + str(os.environ.get('VAR')))"

all:
    @echo -n "echoing: VAR="
    @echo $${VAR}
    @echo -n "printenv: "
    @printenv | grep VAR
    @echo -n "python: "
    @echo $(shell ${PY_VAR})

Output:

echoing: VAR=env_var
printenv: VAR=env_var
python: VAR=None

What am I missing?


Solution

  • In most versions of GNU make, variable exported from the makefile are passed to recipes but they are not passed to the shell function.

    Only in the very latest version of GNU make (4.4 and above), you will see exported variables passed to shell.

    In general it's wrong / a bad idea to use shell in a recipe. It's totally unnecessary because a recipe is already running in a shell.

    If you run PY_VAR explicitly rather than using make's shell function, it will work:

    PY_VAR := python -c "import os; print('VAR=' + str(os.environ.get('VAR')))"
    
    all:
            @echo $$(${PY_VAR})