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?
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With