Using Makefile for task automation

If you’ve written some C/C++ code, or you are familiar with *nix systems, you’ve probably heard about Makefile. Makefile is a file that contains some commands for use with the GNU make build automation system. A typical use would be

$ ./configure && make && make install

However, the usage of Makefile is not limited to just build automation. You can actually use Makefile for many kinds of task automation. Now I’ll show you some simple and common use cases for using Makefile for task automation.

Example 1 - Django project

Imagine you have a Django project in development, you know that each Django project has a powerful file which you can call to execute some useful commands. You can use it to run a server, create a super user, etc. However, typing python with all those arguments takes time. Instead, you can just create a Makefile for easier task execution.

all: local

    python runserver
    python runserver
    python createsuperuser
    python makemigrations
    python migrate

With this Makefile, you can just type make to run a server on your development machine, and use make external to listen to certain IP and port.

Example 2 - Hugo blog

As you may realize, this blog is maintained by the Hugo static website generator. There are several commands which need to be frequently executed. For example, running a test server, generating the website, and publish the updated website to GitHub. I used to have a bash script for each of these purposes. Therefore, I have 3 bash scripts lying in the directory and I have to execute them like this every time

$ ./

It works, of course. However, I want a more elegant way of doing all these tasks. Therefore, I wrote a Makefile for it.

all: build

    hugo --theme=blackburn

    hugo server --bind= --baseUrl="localhost" --theme=blackburn --buildDrafts

    cp -r public/* ../
    cd ../ && \
    git pull && \
    git add --all && \
    git commit -m "update blog content" && \
    git push origin master

Now I can build my blog with make, and publish it to GitHub with make publish. Instead of 3 scripts, I just have one Makefile. Everything looks much cleaner now.

Some things to notice

First, please notice that the commands in Makefile are indented with tabs, not white spaces (white spaces are used in this post). If you write your own Makefile, make sure tab is used.

Second, each command in Makefile is executed in a separate subprocess. Therefore, if you want to switch to another directory and execute some commands there, you should concatenate them with &&. If you want to write them in multiple lines, end the lines (except the last one) with \ (refer to my Makefile for the second example).

comments powered by Disqus