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.
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 .
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With