How to check if a variable is equal to one of two values using the if/or/and functions
The thing that is odd about GNUmake conditionals is that there is no boolean type in make -- everything is a string. So the conditionals all work with the empty string for 'false' and all non-empty strings (including strings like false
and 0
) as being 'true'.
That being said, the fact that eq
is missing is an annoyonace albeit a minor one. Generally you can get what you want from filter
or findstring
, and filter
often allows you to search a whole list of strings to match as in your second example.
If you really need it, you can define your own eq function:
eq = $(and $(findstring $(1),$(2)),$(findstring $(2),$(1)))
Which you unfortunately have to use as $(call eq,
...,
...)
Chris Dodd's answer is good, but there is a corner case for which it provides an incorrect result. If both of the variables being compared are empty (i.e. false) then it will return false. An improved version would be:
eq = $(if $(or $(1),$(2)),$(and $(findstring $(1),$(2)),\
$(findstring $(2),$(1))),1)
This first checks to see either of the arguments are non-empty, and if so uses the previous technique to compare them. Otherwise it returns 1, to indicate that the values are equal as they are both empty.
Depending on your context, consider using the GMSL (GNU Make Standard Library), which is a collection of functions in a make include file "...that provide list and string manipulation, integer arithmetic, associative arrays, stacks, and debugging facilities." See http://gmsl.sourceforge.net/
It has a "string equal" function, seq, as well as a number of other useful manipulators:
TEST_INPUT = $(shell hostname -s)
TEST_OUTPUT = $(if $(or $(call seq,$(TEST_INPUT),hal9000),
$(call seq,$(TEST_INPUT),pipboy)),true,false)
Also, use the $(shell ...) syntax instead of backticks for better handling of newlines.