Testing if a file exists in makefile target, and quitting if not present

Alex Reynolds picture Alex Reynolds · Jan 16, 2013 · Viewed 51.9k times · Source

Is there a way to exit with an error condition if a file does not exist? I am currently doing something like this:

all: foo

foo:
    test -s /opt/local/bin/gsort || echo "GNU sort does not exist! Exiting..." && exit

Running make runs the all target, which runs foo.

The expectation is that if the test -s conditional fails, then the echo/exit statements are executed.

However, even if /usr/bin/gsort exists, I get the result of the echo statement but the exit command does not run. This is the opposite of what I am hoping to accomplish.

What is the correct way to do something like the above?

Answer

KingRadical picture KingRadical · Jul 18, 2013

I realize this is a bit old at this point, but you don't need to even use a subshell to test if a file exists in Make.

It also depends on how you want/expect it to run.

Using the wildcard function, like so:

all: foo
foo:
ifeq (,$(wildcard /opt/local/bin/gsort))
    $(error GNU Sort does not exist!)
endif

is one good way to do it. Note here that the ifeq clause is not indented because it is evaluated before the target itself.

If you want this to happen unconditionally for every target, you can just move it outside of a target:

ifeq (,$(wildcard /opt/local/bin/gsort))
$(error GNU Sort does not exist!)
endif