How to assign the output of a command to a Makefile variable

后端 未结 7 1124
生来不讨喜
生来不讨喜 2020-12-02 05:11

I need to execute some make rules conditionally, only if the Python installed is greater than a certain version (say 2.5).

I thought I could do something like execut

7条回答
  •  遥遥无期
    2020-12-02 05:22

    Beware of recipes like this

    target:
        MY_ID=$(GENERATE_ID);
        echo $MY_ID;
    

    It does two things wrong. The first line in the recipe is executed in a separate shell instance from the second line. The variable is lost in the meantime. Second thing wrong is that the $ is not escaped.

    target:
        MY_ID=$(GENERATE_ID); \
        echo $$MY_ID;
    

    Both problems have been fixed and the variable is useable. The backslash combines both lines to run in one single shell, hence the setting of the variable and the reading of the variable afterwords, works.

    I realize the original post said how to get the results of a shell command into a MAKE variable, and this answer shows how to get it into a shell variable. But other readers may benefit.

    One final improvement, if the consumer expects an "environment variable" to be set, then you have to export it.

    my_shell_script
        echo $MY_ID
    

    would need this in the makefile

    target:
        export MY_ID=$(GENERATE_ID); \
        ./my_shell_script;
    

    Hope that helps someone. In general, one should avoid doing any real work outside of recipes, because if someone use the makefile with '--dry-run' option, to only SEE what it will do, it won't have any undesirable side effects. Every $(shell) call is evaluated at compile time and some real work could accidentally be done. Better to leave the real work, like generating ids, to the inside of the recipes when possible.

提交回复
热议问题