在没有目录的情况下采取行动
如果您只需要知道目录不存在并希望通过创建目录来采取行动,例如,您可以使用普通的 Makefile 目标:
directory = ~/Dropbox
all: | $(directory)
@echo "Continuation regardless of existence of ~/Dropbox"
$(directory):
@echo "Folder $(directory) does not exist"
mkdir -p $@
.PHONY: all
注:
|
表示 make 不关心时间戳(它是一个 仅作为顺序前提条件)。
- 你可以写
false
退出,或者以其他方式解决问题,而不是写 mkdir -p $@
。
如果你还需要在目录存在时运行一系列特定的指令,则无法使用上述方法。换句话说,它等同于:
if [ ! -d "~/Dropbox" ]; then
echo "The ~/Dropbox folder does not exist"
fi
这里没有else
语句。
根据目录的存在进行操作
如果你想要相反的if语句也是可能的:
directory = $(wildcard ~/Dropbox)
all: | $(directory)
@echo "Continuation regardless of existence of ~/Dropbox"
$(directory):
@echo "Folder $(directory) exists"
.PHONY: all $(directory)
这相当于:
if [ -d "~/Dropbox" ]; then
echo "The ~/Dropbox folder does exist"
fi
再次强调,没有else
语句。
对目录的存在和不存在进行操作
这变得有点麻烦,但最终为两种情况提供了很好的目标:
directory = ~/Dropbox
dir_target = $(directory)-$(wildcard $(directory))
dir_present = $(directory)-$(directory)
dir_absent = $(directory)-
all: | $(dir_target)
@echo "Continuation regardless of existence of ~/Dropbox"
$(dir_present):
@echo "Folder $(directory) exists"
$(dir_absent):
@echo "Folder $(directory) does not exist"
.PHONY: all
这相当于:
if [ -d "~/Dropbox" ]; then
echo "The ~/Dropbox folder does exist"
else
echo "The ~/Dropbox folder does not exist"
fi
自然情况下,通配符扩展可能比if-else语句慢。不过,第三种情况可能相当罕见,只是为了完整性而添加的。