Search code examples
makefilegnu-make

Makefile: setting variables only for one target


I have following makefile:

.PHONY: backup other

REMOTE_HOST := server1
DOMAIN_NAME := vm1

VM_IS_RUNNING := $(shell ssh $(REMOTE_HOST) virsh domstate "$(DOMAIN_NAME)")

ifneq ($(.SHELLSTATUS),  0)
    $(error SSH command failed with status $(.SHELLSTATUS))
endif

################################################################################

backup:

ifeq ($(VM_IS_RUNNING),running)

    @echo "VM $(DOMAIN_NAME) is running."
    @exit 0

else

    @echo "VM $(DOMAIN_NAME) is NOT running."
    @exit 0

endif

################################################################################

other:

    @echo "hello"

first, I am setting some variables which are later used in target backup, then I have target backup itself, and last I have another unrelated target other.

How can I run target other without setting the connection variables which I need for my first target ?

I tried moving those inside the backup section, but did not work


Solution

  • If you want to compute the values only in the backup command, then you should compute the values only in the backup command. Remove the VM_IS_RUNNING make variable assignment, and change backup to perform the operation as part of the recipe:

    backup:
        @running=$$(ssh $(REMOTE_HOST) virsh domstate "$(DOMAIN_NAME)") || exit 1; \
        if test "$$running" = running; then \
            echo "VM $(DOMAIN_NAME) is running."; \
        else \
            echo "VM $(DOMAIN_NAME) is NOT running."; \
        fi