Use a help target in your Makefile

on
Sep 08, 2022
in

In one of my previous blog. I wrote how you could make your life easier when you start using Makefile. But when you start using Makefile in many projects. The targets that you use may vary from project to project.

In this blog post I will address a trick how you could write a help target. Lets imagine that we have a project that allow you to build, start and stop a docker container. These names are pretty straightforward. But without looking in the Makefile you never know for sure.

By calling the help target you could list all available targets:

make help
All targets are listed with a help text

When you have a look at the Makefile used for this blog post. It looks like this:

.DEFAULT_GOAL:=help
.PHONY: help
help:  ## Display this help
    $(info Example Makefile for my blog post)
    awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n  make \033[36m<target>\033[0m\n"} /^[a-zA-Z0-9_-]+:.*?##/ { printf "  \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST)

.PHONY: build
build: ## Build the container image
    docker build -t my-container:latest .

.PHONY: stop
stop: ## Stop the container
    docker stop my-named-container > /dev/null 2>&1 || True
    docker rm my-named-container > /dev/null 2>&1 || True

.PHONY: start
start: stop ## Start the container
    docker run --name my-named-container my-container:latest > /dev/null

.PHONY: shell
shell: ## Start a shell session on the container
    docker run -it my-named-container:latest bash

.PHONY: logs
logs: ## Tail the logs of the running container
    docker logs my-named-container -f

$(VERBOSE).SILENT:

You need to add the help target. And for each target you need to supply a help text. And each target needs a prefix with ##.

By adding a help target to your Makefile you make it easier to use for others. But also for yourself because you don’t need to remember each target in the Makefile.

Photo by lalesh aldarwish

Joris has been working with the AWS cloud since 2009 and focussing on building event driven architectures. While working with the cloud from (almost) the start he has seen most of the services being launched. Joris strongly believes in automation and infrastructure as code and is open to learn new things and experiment with them, because that is the way to learn and grow. In his spare time he enjoys running and runs a small micro brewery from his home.
Share this article: Tweet this post / Post on LinkedIn