Barth
Barth

Reputation: 15725

How to check whether a variable contains spaces in a Makefile ?

I want to know whether the variable CHAPTER contains spaces. I tried to use findstring without success :

CHAPTER=default
new:
ifeq (" ",$(findstring " ",$(CHAPTER)))
    $(error Variable contains space)
else
    echo "variable ok"
endif

This code says "variable ok" whereas I would expect the opposite.

What am I doing wrong ?

How should I do ?

Upvotes: 2

Views: 1417

Answers (1)

Eldar Abusalimov
Eldar Abusalimov

Reputation: 25523

Just test whether the variable value is a single word or not using words function:

ifneq (1,$(words [$(CHAPTER)]))
# Things are bad...
endif

Notice the square braces, which help to detect leading/trailing whitespaces as well.

UPD.

Another option is to define a variable with a single space in its value and search the target variable for occurrences.

space :=
space +=

ifneq (,$(findstring,$(space),$(CHAPTER)))
# Things are bad...
endif

Upvotes: 4

Related Questions