gnu makefile: shell function execution order in a recipe

Viewed 1084

I'm using $(shell ...) gnu make function in a Makefile recipe, and it runs first before the preceding rows. Why?

A very simple example:

.PHONY: all
all:
    @echo 1
    @echo $(eval a=$(shell echo 2a 1>&2))2b
    @echo 3 $(a)

The output is:

2a
1
2b
3

First runs the $(shell ...) line (2a), then the other lines. How can I manage to run the $(shell ...) function when its row runs in the recipe, in this order?

1
2a
2b
3

Edit:

Without $(shell ...) it works as I expected:

.PHONY: all
all:
    @echo 1
    $(eval a=a)
    @echo 2 $(a)
    $(eval a=b)
    @echo 3 $(a)

Output:

1
2 a
3 b

Edit 2:

Here is a part of the original Makefile. The pieces at >>> show the essence of my problem: I want to put the output of udisksctl into a make variable instead of file $@.loop (and do the same with $@.mount).

$(HDIMG): $(BOOTBLOCK_MBR_BIN) $(BOOTBLOCK_EXT2_BIN) $(LOADER_BIN) | $(DESTDIR)
        dd if=/dev/zero of=$@.ext2 bs=1 seek=$(PSIZEB) count=0 2>/dev/null
        $(MKFSEXT2) -F $@.ext2 >/dev/null
        dd if=$(word 2,$^) of=$@.ext2 conv=notrunc 2>/dev/null
        cp $< $@
        dd if=/dev/zero of=$@ bs=1 seek=$(HDSIZEB) count=0 2>/dev/null
        echo $(PFDISK) | $(TR) | $(FDISK) $@ >/dev/null
        dd if=$@.ext2 of=$@ bs=512 seek=$(PSTART) conv=sparse,notrunc iflag=fullblock 2>/dev/null
>>>     udisksctl loop-setup --file $@ --offset $(PSTARTB) --size $(PSIZEB) >$@.loop
        sed -i -e 's/.* //;s/\.//' $@.loop
        cat $@.loop
>>>     udisksctl mount --block-device $$(cat $@.loop) >$@.mount
        sed -i -e 's/.* //;s/\.//' $@.mount
        cat $@.mount
        #
        mkdir -p $$(cat $@.mount)/boot/
        cp $(word 2,$^) $$(cat $@.mount)/boot/
        #/sbin/filefrag -b512 -e /
        #
        udisksctl unmount --block-device $$(cat $@.loop)
        udisksctl loop-delete --block-device $$(cat $@.loop)
        rm $@.loop
1 Answers

When make runs a recipe, it first expands all variables/functions in it, and then runs the shell commands line by line.

You can work around that by executing every shell command with $(shell ...), or, in your case, by using $(info ...) instead of echo:

.PHONY: all
all:
    $(info 1)
    $(info $(eval a=$(shell echo 2a 1>&2))2b)
    $(info 3 $(a))

Output:

1
2a
2b
3
make: Nothing to be done for 'all'.

The Nothing to be done for 'all'. part is caused by the fact that after expanding the functions, the recipe is effectively empty (has 0 shell commands). Adding a no-op command (e.g. @true) to it removes the message.

Related