20

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

3 Answers 3

38

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? 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
1

this has worked for me and I find it more readable

.PHONY: foo
foo: export FOO="this-is-foo"
foo:
    echo "{$$FOO}"

but if the env variable is a dynamic value then using && \ makes more sense

.PHONY: foo
foo:
    export FOO="this-is-foo" && \
    echo "{$$FOO}"
1
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center. Commented Sep 26 at 17:00
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.