Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Makefile variable assignment error in echo

Tags:

makefile

I have make file target like this

foo: 
    i = 1
    @echo $(i)

when I run the make file like this:

$ make foo 

i = 1
make: i: Command not found
Makefile:2: recipe for target 'foo' failed
make: [foo] Error 127

But if I do not give spaces in assignment (i.e)

i=1

Then no errors but no output, value of i is not printed

like image 723
Ibrahim Quraish Avatar asked Feb 10 '17 11:02

Ibrahim Quraish


1 Answers

The first attempt runs the command i with the parameters = and 2. A proper assignment in the shell has no spaces on either side of the equals sign.

Your second problem is that a recipe on two physical lines will run two unrelated shell instances. The first sets a variable to a value, then exits and loses the variable. The second, unrelated instance has no idea what the first did, and of course has no trace of the variable assignment. The fix for that is to merge the two into a single line logically (you can still split the lines over several physical lines as long as you have a semicolon between them):

foo: 
    i=1; \
    echo "$${i}"

Notice also how we need to double the dollar signs in order to prevent make from interpreting them; and the proper use of quotes around strings in the shell. (In this particular case we know the string doesn't contain any shell metacharacters; but many beginners stumble over this as well.)

GNU Make alternatively allows you to specify .ONESHELL which forces the commands in the recipe to be evaluated all in a single shell instance;

.ONESHELL:
foo: 
    i=1
    echo "$${i}"
like image 199
tripleee Avatar answered Sep 24 '22 14:09

tripleee