17

We have below task in Makefile:

test:
    export SOME_ENV=someTest
    go test -tags=integration -v -race  ./tests/integrationtest/...

on shell prompt, SOME_ENV is set and the next command(go test) internally picks .someTest.env file

 $ export SOME_ENV=someTest
 $ go test -tags=integration -v -race  ./tests/integrationtest/...

but the Makefile approach doesn't work

Why environment variable is not set using Makefile approach?

Note: we have another tasks in Makefile that should not be influence with this export

1

2 Answers 2

32

Each line in a recipe is executed using a separate shell invocation. Thus

export SOME_ENV=someTest

is executed, then in a new shell,

go test ...

and the latter doesn’t see the environment variable.

You should export the variable using Make’s constructs:

export SOME_ENV := someTest

test:
        go test ...

or specify the variable inline:

test:
        SOME_ENV=someTest go test ...

or ensure both lines are run in the same shell:

test:
        export SOME_ENV=someTest && \
        go test ...
2
  • 1
    I couldn't get the final approach to work. Is there btw a way to expose SOME_ENV to the rest of the commands without export?
    – jtlz2
    Commented Jun 23, 2022 at 7:09
  • That depends on exactly where you need to expose SOME_ENV. If you need to have it in child processes’ environments, you need to export it, either from Make or the shell. Commented Jun 23, 2022 at 8:17
0

As @Stephen kitt pointed out the export will take effect in a separate shell and not the one you are calling the make, his answer gave a solution if the command that preceds the export also will be run using make, but you can do something like this if you want to use it out of make:

print_my_env:
    echo 'export MY_ENV="blue"'

then:

eval "$(make print_my_env)"

now if you run echo "$MY_ENV" you should get your env.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .