bsr
bsr

Reputation: 58742

Makefile: set the environment variables output by a command

I am trying to write a make target, where it sets the env. variables obtained by a shell command.

gcloud beta emulators datastore env-init command on the terminal output few exports statement like (doesn't set, but just echoes / prints).

export DATASTORE_EMULATOR_HOST=localhost:8432
export DATASTORE_PROJECT_ID=my-project-id

Normally, I have to copy and paste these lines into the terminal to set the variables.

Is it possible to make these printed export statement to execute so they will be set on the shell. I tried like, but didn't work.

target:
    @export JAVA_HOME=$(JAVA_HOME); \
    $(shell gcloud beta emulators datastore env-init); \
    go run src/main.go

it prints out the script output if I do like,

target:
    export JAVA_HOME=$(JAVA_HOME); \
    gcloud beta emulators datastore env-init \
    go run src/main.go

Similar to the JAVA_HOME, how can I also source output of gcloud beta emulators datastore env-init command (which are 4 lines of export commands) so they are set in the environment.

so I want something like, in effect,

target:
        export JAVA_HOME=$(JAVA_HOME); \
        export DATASTORE_EMULATOR_HOST=localhost:8432 \
        export DATASTORE_PROJECT_ID=my-project-id \
        go run src/main.go

thanks. bsr

Upvotes: 2

Views: 2389

Answers (1)

Florian Weimer
Florian Weimer

Reputation: 33747

The output printed by make does not actually affect the environment contents of subprocesses.

If the variable assignments do not appear to have any effect, that's because make runs each line in a separate subshell, each with fresh environment. You need to join the commands together like this:

target:
    export JAVA_HOME=$(JAVA_HOME); \
    eval "$$(gcloud beta emulators datastore env-init)"; \
    go run src/main.go

The eval is necessary so that the output of the gcloud command is evaluated in the current shell, and not a subshell. Also note the semicolon at the end of the second line of the recipe.

Upvotes: 1

Related Questions