Mahyar
Mahyar

Reputation: 1121

use variable after if condition in a rule

so I need to add some logic to an existing makefile. here's the rule I'm working on:

deploy:
ifneq ($(filter $(SERVICE),$(AVAILABLE_SERVICES)),)
    SA=$(SERVICE)
else
    SA="default"
endif
    export SA
    # do something ...
    # do something else

I essentially need to export SA variable based on a condition, but this wouldn't work fine since I think SA after condition does not related to the SA inside the condition

Any suggestion on how to set the variable inside if statement and then use it afterwards? (within the rule)

Upvotes: 0

Views: 52

Answers (1)

MadScientist
MadScientist

Reputation: 100836

Based on your example I don't know why you need to do this "within the rule". The answer to this question is absolutely vital to a correct response.

If your example is accurate and you're using make variables SERVICE and AVAILABLE_SERVICES then I don't see any reason that you can't put the variable assignment outside of the rule:

ifneq ($(filter $(SERVICE),$(AVAILABLE_SERVICES)),)
  export SA = $(SERVICE)
else
  export SA = default
endif
deploy:
        # do something ...
        # do something else

If the variables you're relying on are not make variables, then you have to implement the entire thing in the shell instead of using make constructs like ifneq, filter, etc.

If the latter remember that each logical line of a recipe is run in a different shell so if you want to set shell variables that are used in future statements you need to make those lines in the recipe one logical line (by adding a backslash at the end, which probably also requires you to add a shell statement separator ; between them).

Upvotes: 3

Related Questions