简体   繁体   中英

Why does `?=` (“set if absent”) cause make to unset an environment variable?

I have a makefile as the following

.PHONY: check
check:
    ./check.sh

.PHONY: bar
bar: ENV_TEST ?= bar_env_test
bar:
    echo $(ENV_TEST)

and a script file ( check.sh )

#!/bin/bash

echo $ENV_TEST
echo $ENV_TEST_2

Firstly, I export both values of ENV_TEST and ENV_TEST_2 variables

export ENV_TEST=env_test
export ENV_TEST_2=env_test_2

Then run make check and get the following output

./check.sh

env_test_2

the value of ENV_TEST_2 was printed correctly but the value of ENV_TEST was empty. My expected output is something like this

./check.sh
env_test
env_test_2

Does anyone know what happened to ENV_TEST environment variable?

This is part of a response :

When you add the export directive to the target-specific assignment, it will be ok:

check:
    @ ./check.sh

bar: export ENV_TEST ?= bar_env_test
bar:
    @ echo $(ENV_TEST)

.PHONY: check bar

And the result:

$ export ENV_TEST=env_test
$ export ENV_TEST_2=env_test_2
$ make check
env_test
env_test_2
$ make bar
env_test
$ unset ENV_TEST
$ make check

env_test_2
$ make bar
bar_env_test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM