Makefile variable assignment error in echo

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

Leave a Comment