How to pass argument to Makefile from command line?
I understand I can do
$ make action VAR="value"
$ value
with Makefile
VAR = "default"
action:
@echo $(VAR)
How do I get the following behavior?
$ make action value
value
?
How about
$make action value1 value2
value1 value2
You probably shouldn't do this; you're breaking the basic pattern of how Make works. But here it is:
EDIT:
To explain the first command,
$(MAKECMDGOALS)
is the list of "targets" spelled out on the command line, e.g. "action value1 value2".$@
is an automatic variable for the name of the target of the rule, in this case "action".filter-out
is a function that removes some elements from a list. So$(filter-out bar, foo bar baz)
returnsfoo baz
(it can be more subtle, but we don't need subtlety here).Put these together and
$(filter-out $@,$(MAKECMDGOALS))
returns the list of targets specified on the command line other than "action", which might be "value1 value2".Here is a generic working solution based on @Beta's
I'm using GNU Make 4.1 with
SHELL=/bin/bash
atop my Makefile, so YMMV!This allows us to accept extra arguments (by doing nothing when we get a job that doesn't match, rather than throwing an error).
And this is a macro which gets the args for us:
Here is a job which might call this one:
The result would be:
Note! You might be better off using a "Taskfile", which is a bash pattern that works similarly to make, only without the nuances of Maketools. See https://github.com/adriancooney/Taskfile
don't try to do this
instead create script:
and do this:
for more explanation why do this and caveats of makefile hackery read my answer to another very similar but seemingly not duplicate question: Passing arguments to "make run"
Much easier aproach. Consider a task:
Now when I want to call it I just run something like:
AT="build assets" make provision
or just:
make provision
in this caseAT
is an empty string