Add environment variable for duration of Make task

12,225

Solution 1

“Task” is not common make terminology. I assume that you mean a rule. If you're using GNU make, you can set a variable for a specific rule, or more precisely, for a specific target.

test-results: export PATH := $(shell npm bin):$$PATH
test-results: test-binary1 test-binary2 test-data2 reference-test-results
        test-binary1 >test-results
        test-binary2 test-data2 >>test-results
        diff test-results reference-test-results

Note that the assignment is in make syntax, which is not the same as shell syntax. And note that when modifying a variable, you must use eager (“expanded”) assignment, not the = lazy assignment which would create a circular reference.

Solution 2

I think you are looking for the export command in bash (or the equivalent in your shell of choice): http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_02.html

Share:
12,225

Related videos on Youtube

josh
Author by

josh

Updated on September 18, 2022

Comments

  • josh
    josh almost 2 years

    I'm using make to handle building files for my application, and those build processes use node modules. Since I install those node modules locally, I have to specify in my $PATH where to call the executables, e.g. PATH=$(npm bin):$PATH.

    I've set up a variable within my Makefile, NPMEXEC := PATH=$(shell npm bin):$$PATH, and prepend this to my commands when I need to. However, for some longer tasks such as during testing that run multiple commands, it would be convenient to have that PATH assignment occur during the entire duration of the task, kind of like pushd/popd. Is that possible?

    • meuh
      meuh almost 8 years
      I'm not clear what you want. Why not just put at the start of your makefile export PATH:=$(shell npm bin):$(PATH)?
    • josh
      josh almost 8 years
      @meuh I would prefer to do it per task since I'm not only handling building Node.js files, and I don't want to mess with the PATH in the other cases.
    • meuh
      meuh almost 8 years
      So, couldnt you add your multiple commands as a new target in the makefile, and as command set the PATH before calling make again on the multiple commands?
    • josh
      josh almost 8 years
      @meuh Do you mean in the actual command set the PATH, e.g. PATH=<...> make test? To me it makes more sense to just be able to call make test and let the Makefile/make handle it. Of course I can set the PATH in front of each command in the make task, but it clutters up the Makefile.
  • josh
    josh almost 8 years
    Not export, because that will persist after I finish my task. I want the variable to be temporary for the duration of the task.
  • sysadmiral
    sysadmiral almost 8 years
    You can unset after the task? Else you will need to "pass" the variable between tasks.