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

The best answers to the question “How to assign the output of a command to a Makefile variable” in the category Dev.


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 executing:

python -c 'import sys; print int(sys.version_info >= (2,5))'

and then using the output (‘1’ if ok, ‘0’ otherwise) in a ifeq make statement.

In a simple bash shell script it’s just:

MY_VAR=`python -c 'import sys; print int(sys.version_info >= (2,5))'`

but that doesn’t work in a Makefile.

Any suggestions? I could use any other sensible workaround to achieve this.


Beware of recipes like this

    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.

    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.

    echo $MY_ID

would need this in the makefile

    export MY_ID=$(GENERATE_ID); \

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.


Use the Make shell builtin like in MY_VAR=$(shell echo whatever)

[email protected]:~$make
MY_VAR IS whatever

[email protected]:~$ cat Makefile 
MY_VAR := $(shell echo whatever)

    @echo MY_VAR IS $(MY_VAR)


Here’s a bit more complicated example with piping and variable assignment inside recipe:

    # Getting pod name
    @eval $$(minikube docker-env) ;\
    $(eval PODNAME=$(shell sh -c "kubectl get pods | grep profile-posts-api | grep Running" | awk '{print $$1}'))
    echo $(PODNAME)


Wrapping the assignment in an eval is working for me.

# dependency on .PHONY prevents Make from 
# thinking there's `nothing to be done`
set_opts: .PHONY
  $(eval DOCKER_OPTS = -v $(shell mktemp -d -p /scratch):/output)