In the clean section of my Makefile
I am trying to check if the file exists before deleting permanently. I use this code but I receive errors.
What\'s w
The second top answer mentions ifeq
, however, it fails to mention that these must be on the same level 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
I was trying:
[ -f $(PROGRAM) ] && cp -f $(PROGRAM) $(INSTALLDIR)
And the positive case worked but my ubuntu bash shell calls this TRUE and breaks on the copy:
[ -f ] && cp -f /home/user/proto/../bin/
cp: missing destination file operand after '/home/user/proto/../bin/'
After getting this error, I google how to check if a file exists in make, and this is the answer...
Or just put it on one line, as make
likes it:
if [ -a myApp ]; then rm myApp; fi;
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
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
And make clean
always works without any error messages!
FILE1 = /usr/bin/perl
FILE2 = /nofile
ifeq ($(shell test -e $(FILE1) && echo -n yes),yes)
RESULT1=$(FILE1) exists.
else
RESULT1=$(FILE1) does not exist.
endif
ifeq ($(shell test -e $(FILE2) && echo -n yes),yes)
RESULT2=$(FILE2) exists.
else
RESULT2=$(FILE2) does not exist.
endif
all:
@echo $(RESULT1)
@echo $(RESULT2)
execution results:
bash> make
/usr/bin/perl exists.
/nofile does not exist.