how to check if a directory does "not exist" in Makefile? if [ ! -d ... ] returns always true

Viewed 1652

I want to add a couple of lines so that the make process can error out if certain directory (set by a Makefile variable DIR1) doesn't exist. Here is the added part but this errors out even if I the directory set by DIR1 exists. For example, I made the directory called 'dir1' but make errors out. What is wrong?

DIR1 = dir1

.PHONY : check_dir

$(info DIR1 = $(DIR1))

check_dir:  
    if [ ! -d $(DIR1) ]; then \
        $(error "DIR1 does not exist! check Makefile!"); \
    fi

This is the run result.(I have directory called dir1 in current directory).

> ckim@chan-ubuntu:~/testmake/test1$ make  
> DIR1 = dir1 Makefile:8:
> *** "DIR1 does not exist! check Makefile!".  Stop.
1 Answers

The $(error ...) is systematically expanded by make before passing the recipe to the shell. So the error is raised each time this recipe is run, independently from the result of you shell if statement.

Use only shell constructs:

check_dir:  
    if [ ! -d "$(DIR1)" ]; then \
        echo "$(DIR1) does not exist! check Makefile!"; \
        exit 1; \
    fi

Or (a bit more compact, if not easier to understand):

MESSAGE := $(DIR1) does not exist! check Makefile!
check_dir:  
    @[ -d "$(DIR1)" ] || { echo "$(MESSAGE)"; exit 1; }

There are other possibilities like:

check_dir: $(DIR1)

$(DIR1):
    $(error $(DIR1) does not exist! check Makefile!)

But this does not make a difference between a file named $(DIR1) and a directory.

Note: if you want to raise an error when make parses the Makefile and discovers the directory does not exist, you can use the shell function and a make conditional:

OK := $(shell if [ -d $(DIR1) ]; then echo "ok"; fi)

ifeq ($(OK),)
$(error $(DIR1) does not exist! check Makefile!)
endif
Related