如果变量为空,如何跳过Make目标?

时间:2019-11-27 01:43:04

标签: makefile gnu-make

考虑以下makefile文件

# If current commit is not part of a PR, the PULL_REQUEST_ID variable will be empty.
PULL_REQUEST_ID := $(shell git ls-remote origin 'pull/*/head' | grep -F -f <(git rev-parse HEAD) | awk -F'/' '{print $3}')

# if PULL_REQUEST_ID is empty, I want 'make deploy-to-staging' to be no-op
.PHONY deploy-to-staging
deploy-to-staging: update-some-files apply-those-files-to-k8s

2 个答案:

答案 0 :(得分:2)

使用条件指令ifneq

deploy-to-staging: update-some-files apply-those-files-to-k8s
ifneq ($(PULL_REQUEST_ID),'')
        git push ...  # or whatever
else
        echo "Refusing to deploy non-pull-request to staging"
endif

答案 1 :(得分:1)

如果要部署的所有操作都是目标的先决条件,则可以有条件地定义这些先决条件,即:

$ cat Makefile
ifneq ($(PULL_REQUEST_ID),)
  deploy-to-staging:  update-some-files apply-those-files-to-k8s
endif

.PHONY: deploy-to-staging
deploy-to-staging:

.PHONY: update-some-files
update-some-files:
        echo Updating...

.PHONY: apply-those-files-to-k8s
apply-those-files-to-k8s:
        echo Applying...

输出:

$ make deploy-to-staging
make: Nothing to be done for 'deploy-to-staging'.

$ make deploy-to-staging PULL_REQUEST_ID=foo
echo Updating...
Updating...
echo Applying...
Applying...