Using variables with export in Makefile

Viewed 29

I would like to add some variables and echo commands in a Makefile. The section is:

.PHONY: run_harness
run_harness: link_dirs
    @mkdir -p $(LOG_DIR)
    @set -o pipefail && $(PYTHON3_CMD) code/main.py $(RUN_ARGS) --action="run_harness" 2>&1 | tee $(LOG_DIR)/stdout.txt
    @set -o pipefail && $(PYTHON3_CMD) scripts/print_harness_result.py $(RUN_ARGS) 2>&1 | tee -a $(LOG_DIR)/stdout.txt

and I want to add

.PHONY: run_harness
run_harness: link_dirs
    @mkdir -p $(LOG_DIR)
    ########
    @export WRK="test"
    @export startTime=$(date +%s)
    @echo $(WRK), $(startTime)
    ########
    @set -o pipefail && $(PYTHON3_CMD) code/main.py $(RUN_ARGS) --action="run_harness" 2>&1 | tee $(LOG_DIR)/stdout.txt
    @set -o pipefail && $(PYTHON3_CMD) scripts/print_harness_result.py $(RUN_ARGS) 2>&1 | tee -a $(LOG_DIR)/stdout.txt

But those export and echo don't work because I get , in the output which mean both $(WRK) and $(startTime) are empty. How can I fix that?

UPDATE:

The following change

@mkdir -p $(LOG_DIR)
export WRK="3d-unet"; \
export startTime=$(date +%s); \
echo $(WRK), $(startTime) ;

doesn't work due to this error

1 Answers

Each line in a recipe is executed in a separate shell. You need to put all shell commands on one line, separated by semicolons (and possibly use line continuation with backslash newline for readability). And you must reference shell variables with $$name (not with make variable $(name)). Note that make replaces a $$ with a single $ for the shell.

foo: bar
     export x=hello y=world; \
     echo "$$x" "$$y"
     
Related