How do I check if file exists in Makefile so I can delete it?
Solution 1:
It's strange to see so many people using shell scripting for this. I was looking for a way to use native makefile syntax, because I'm writing this outside of any target. You can use the wildcard
function to check if file exists:
ifeq ($(UNAME),Darwin)
SHELL := /opt/local/bin/bash
OS_X := true
else ifneq (,$(wildcard /etc/redhat-release))
OS_RHEL := true
else
OS_DEB := true
SHELL := /bin/bash
endif
Update:
I found a way which is really working for me:
ifneq ("$(wildcard $(PATH_TO_FILE))","")
FILE_EXISTS = 1
else
FILE_EXISTS = 0
endif
Solution 2:
The second top answer mentions ifeq
, however, it fails to mention that this ifeq
must be at the same indentation level in the makefile as the name of the target, e.g., to download a file only if it doesn't currently exist, the following code could be used:
download:
ifeq (,$(wildcard ./glob.c))
curl … -o glob.c
endif
# THIS DOES NOT WORK!
download:
ifeq (,$(wildcard ./glob.c))
curl … -o glob.c
endif
Solution 3:
The problem is when you split your command over multiple lines. So, you can either use the \
at the end of lines for continuation as above or you can get everything on one line with the &&
operator in bash.
Then you can use a test
command to test if the file does exist, e.g.:
test -f myApp && echo File does exist
-f file
True if file exists and is a regular file.
-s file
True if file exists and has a size greater than zero.
or does not:
test -f myApp || echo File does not exist
test ! -f myApp && echo File does not exist
The test
is equivalent to [
command.
[ -f myApp ] && rm myApp # remove myApp if it exists
and it would work as in your original example.
See: help [
or help test
for further syntax.
Solution 4:
It may need a backslash on the end of the line for continuation (although perhaps that depends on the version of make):
if [ -a myApp ] ; \
then \
rm myApp ; \
fi;