简介
Makefile 是用于自动构建(build automation),天生的命令行工具。而且可以顺序执行
示例
docker-sshd项目中有一个Makefile
,如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
NAME := sshd
TAG := latest
IMAGE_NAME := panubo/$(NAME)
.PHONY: help build push clean
help:
@printf "$$(grep -hE '^\S+:.*##' $(MAKEFILE_LIST) | sed -e 's/:.*##\s*/:/' -e 's/^\(.\+\):\(.*\)/\\x1b[36m\1\\x1b[m:\2/' | column -c2 -t -s :)\n"
build: ## Builds docker image latest
docker build --pull -t $(IMAGE_NAME):latest .
push: ## Pushes the docker image to hub.docker.com
# Don't --pull here, we don't want any last minute upsteam changes
docker build -t $(IMAGE_NAME):$(TAG) .
docker tag $(IMAGE_NAME):$(TAG) $(IMAGE_NAME):latest
docker push $(IMAGE_NAME):$(TAG)
docker push $(IMAGE_NAME):latest
clean: ## Remove built images
docker rmi $(IMAGE_NAME):latest || true
docker rmi $(IMAGE_NAME):$(TAG) || true
通过执行 make clean
和 make push
等操作,可以快速执行操作;也可以 make
顺序执行。
Cheat Sheet
.PHONY
.PHONY
字段所指定的命令,将是makefile的命令,而不是shell中的命令。
如:
1
2
3
4
5
6
7
# 不会执行terminal中的docker命令
.PHONY: docker
docker:
@echo installing docker
install_mysql:
docker
双冒号
::
标明target重复。有时候,我们想要设置一个模板,执行target前操作某些行为,执行target后执行某些行为。那么我们可以这样做:
1
2
3
4
5
6
7
8
test::
执行前
test::
执行
test::
执行后
如果想要做到动态话,那么我们就要将前后target的名字变成变量:
1
2
3
4
5
6
7
8
9
10
11
FIRST_GOAL := test
LAST_GOAL := test
$(FIRST_GOAL)::
执行前
test::
执行
$(LAST_GOAL)::
执行后
点击完整示例。
others
1
2
3
4
5
6
7
8
9
# 当前工作路径
cur_work_dir:
@echo "The current working directory: $(CURDIR)"
# makefile所在的路径
# https://stackoverflow.com/a/23324703/4883754
ROOT_DIR:=$(shell dirname $(realpath $(firstword $(MAKEFILE_LIST))))
cur_dir:
@echo "The current directory: $(ROOT_DIR)"