Makefile variable assignment error in echo

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


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}"

In the first case you instruct the make to run a shell command: i = 1.

If you want a variable inside Makefile you should set without leading spaces/tabs.

I assume you use GNU's make and you want to check Recipe Syntax (or similar for other makes):

A variable definition in a “rule context” which is indented by a tab as the first character on the line, will be considered part of a recipe, not a make variable definition, and passed to the shell.