How do I check if file exists in Makefile?
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 ifeq (,$(wildcard /etc/redhat-release)) OS_RHEL := true else OS_DEB := true SHELL := /bin/bash endif
I found a way which is really working for me:
ifneq ("$(wildcard $(PATH_TO_FILE))","") FILE_EXISTS = 1 else FILE_EXISTS = 0 endif
In the clean section of my makefle I am trying to check if the file exists before deleting permanently. I use this code but I receive errors.
What's wrong with it?
if [ -a myApp ] then rm myApp fi
I get this error message
f [ -a myApp ] /bin/sh: Syntax error: end of file unexpected (expecting "then") make: *** [clean] Error 2
Missing a semicolon
if [ -a myApp ]; then rm myApp fi
However, I assume you are checking for existence before deletion to prevent an error message. If so, you can just use
rm -f myApp which "forces" delete, i.e. doesn't error out if the file didn't exist.
You can simply use
test command to test if the file does exist, e.g.:
test -f myApp && echo File does exist
-f fileTrue if file exists and is a regular file.
-s fileTrue 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
test is equivalent to
[ command. See:
help [ or
help test for further syntax.
One line solution:
[ -f ./myfile ] && echo exists
One line solution with error action:
[ -f ./myfile ] && echo exists || echo not exists
Example used in my
make clean directives:
clean: @[ -f ./myfile ] && rm myfile || true
make clean always works without any error messages!