如何检查文件是否存在于Makefile中?

在我makefle的干净部分,我试图检查文件是否永久删除之前存在。 我使用这个代码,但我收到错误。

它出什么问题了?

if [ -a myApp ] then rm myApp fi 

我得到这个错误消息

  f [ -a myApp ] /bin/sh: Syntax error: end of file unexpected (expecting "then") make: *** [clean] Error 2 

它可能需要一个反斜线在行尾以延续(虽然也许取决于make的版本):

 if [ -a myApp ] ; \ then \ rm myApp ; \ fi; 

看到有这么多人使用shell脚本,这很奇怪。 我正在寻找一种使用本机makefile语法的方法,因为我正在写任何目标以外的东西。 您可以使用wildcard函数来检查文件是否存在:

  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 

更新:

我发现了一种真正为我工作的方式:

 ifneq ("$(wildcard $(PATH_TO_FILE))","") FILE_EXISTS = 1 else FILE_EXISTS = 0 endif 

您可以简单地使用test命令来testing文件是否存在,例如:

 test -f myApp && echo File does exist 

-f file如果文件存在并且是常规文件,则为true。

-s file如果文件存在并且大小大于零,则为true。

或者不:

 test -f myApp || echo File does not exist test ! -f myApp && echo File does not exist 

test等同于[命令。 请参阅: help [help test更多的语法。

或者把它放在一条线上,就像make一样:

 if [ -a myApp ]; then rm myApp; fi; 

缺less分号

 if [ -a myApp ]; then rm myApp fi 

但是,我假设您在删除之前检查是否存在以防止出现错误消息。 如果是这样,你可以使用rm -f myApp这个“强制”删除,也就是说如果文件不存在就不会出错。

 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) 

执行结果:

 bash> make /usr/bin/perl exists. /nofile does not exist. 

一行解决scheme:

  [ -f ./myfile ] && echo exists 

一行解决scheme,错误操作:

  [ -f ./myfile ] && echo exists || echo not exists 

在我的make clean指令中使用的例子:

 clean: @[ -f ./myfile ] && rm myfile || true 

make clean工作,没有任何错误信息!