Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Makefile variable to result of command in rule

Tags:

git

makefile

I am trying to assign the result of a command to a variable in GNU make. It works if I do it outside the rule:

$ cat stack.mk
GIT_BRANCH=$(shell git rev-parse --abbrev-ref HEAD)

all:
    @echo Git branch is $(GIT_BRANCH)

$ make -f stack.mk all
Git branch is dev

But not if I put it in the rule body:

$ cat stack.mk
all:
    export GIT_BRANCH=$(shell git rev-parse --abbrev-ref HEAD)
    @echo Git branch is $(GIT_BRANCH)

$ make -f stack.mk all
export GIT_BRANCH=dev
Git branch is

Is it possible to assign variables in a rule. At this point I would like to assign the results of a couple of git commands to shell/Makefile variables.

like image 308
Stephen Rasku Avatar asked Jan 19 '16 23:01

Stephen Rasku


People also ask

How do I set a variable in a makefile?

If you want to set the variable in the makefile even though it was set with a command argument, you can use an override directive, which is a line that looks like this: To append more text to a variable defined on the command line, use: See section Appending More Text to Variables .

What is make command in makefile?

I can literally go on, Use Cases are endless and if you still have not tried Make commands in MakeFile, then I insist “ Go, Try and Create Magic ” Make command is a rule that can be set for a script or block of commands. Consider it as a one-word rule that you would set to execute a bunch of commands in series.

What is the difference between Makefile and make rule?

Ideally, if you run only “ make” through CLI, then the first rule from MakeFile will run. And if “ make rule ” is executed through CLI, then that specific rule will run. It can be used with almost all languages similar to Python.

How do you write a target rule in makefile?

The general syntax of a Makefile target rule is − target [target...] : [dependent ....] [ command ...] In the above code, the arguments in brackets are optional and ellipsis means one or more. Here, note that the tab to preface each command is required.


1 Answers

Yes, if you are trying to set a Makefile variable, you can do it using eval function.

all:
    $(eval GIT_BRANCH=$(shell git rev-parse --abbrev-ref HEAD))
    echo Git branch is $(GIT_BRANCH)
like image 68
merlin2011 Avatar answered Oct 10 '22 12:10

merlin2011