# 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 manage.py 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 manage.py with all those arguments takes time. Instead, you can just create a Makefile for easier task execution. all: local local: python manage.py runserver external: python manage.py runserver 1.2.3.4:9999 super: python manage.py createsuperuser migrate: python manage.py makemigrations python manage.py 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 $ ./publish.sh


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

build:
hugo --theme=blackburn

test:
hugo server --bind=127.0.0.1 --baseUrl="localhost" --theme=blackburn --buildDrafts

publish:
cp -r public/* ../koallen.github.io
cd ../koallen.github.io && \
git pull && \
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).