在没有目录时采取行动
如果您只需要知道一个目录是否不存在并想通过例如创建它来采取行动,您可以使用普通的 Makefile 目标:
directory = ~/Dropbox
all: | $(directory)
@echo "Continuation regardless of existence of ~/Dropbox"
$(directory):
@echo "Folder $(directory) does not exist"
mkdir -p $@
.PHONY: all
备注:
如果您还需要在存在目录时运行特定系列的指令,则不能使用上述指令。换句话说,它相当于:
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-statement 慢。但是,第三种情况可能很少见,只是为了完整性而添加。