13

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

overexchange
  • 1,466
  • 10
  • 29
  • 46
  • Related: [What is a subshell (in the context of the documentation of make)?](https://unix.stackexchange.com/questions/23698/what-is-a-subshell-in-the-context-of-the-documentation-of-make) – steeldriver Jun 30 '21 at 15:07

1 Answers1

25

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 ...
Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164
  • 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 Jun 23 '22 at 07: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. – Stephen Kitt Jun 23 '22 at 08:17