Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If-equals statement in makefile as a one-liner

Tags:

bash

makefile

The following works as intended:

branch := $(shell git rev-parse --abbrev-ref HEAD)

ifeq ($(branch), master)
    ami_regions = us-west-2
endif

show_regions:
    echo $(ami_regions)

How could this ifeq statement be written as a one-liner, where the variable is set if the condition passes, otherwise sets the variable as another value or simply leaves it unset?

like image 437
alkalinecoffee Avatar asked Jan 09 '19 14:01

alkalinecoffee


People also ask

What is $$ in Makefile?

Commands and executionIf you want a string to have a dollar sign, you can use $$ . This is how to use a shell variable in bash or sh . Note the differences between Makefile variables and Shell variables in this next example.

What is Ifneq in Makefile?

The ifneq directive begins the conditional, and specifies the condition. It contains two arguments, separated by a comma and surrounded by parentheses. Variable substitution is performed on both arguments and then they are compared.


1 Answers

That should be possible. Try from chapter 8.4 one conditional in combination with string search from chapter 8.2 of the manual:

branch := $(shell git rev-parse --abbrev-ref HEAD)

ami_regions = $(if $(findstring master,$(branch)),us-west-2,)

show_regions:
    echo $(ami_regions)

The function $if will return the value from the then branch if $findstring returns anything. $findstring will return master if $(branch) contains the string master. The downside is that this will also match something like master-tests.

To make this match exactly master you will have to rely on bash: $(shell if [ master = $(branch) ]; then echo "true"; fi ). But then you also have to take care that $(branch) does not contain shell code with side effects (usually not).

Update

Renaud Pacalet and MadScientist in the comments have given improvements to the use of $findstring: Use $filter or $patsubst. As the string you are searching isn't a pattern, using simple $subst instead of $patsubst is also possible.

$(if $(patsubst master,,$(branch)),,us-west-2)

Notice that us-west-2 moved to the else branch, as $patsubst/subst replace the found string with the empty string leading to a false condition if the substitution is successful.

$(if $(filter master,$(branch)),us-west-2,)

$filter returns words from the input that match the supplied patter. Because the pattern is a single word, in this case it only returns exact matches.

So basically both alternatives give similar results. Differences arise if $branch contains spaces: Spaces between removed words will be returned by $patsubst, while $filter only returns matches. Git doesn't allow branches with spaces, this case should not occur.

like image 194
Loebl Avatar answered Oct 06 '22 21:10

Loebl