Automating Tasks with make

Learn how to use the make command to automate tasks.

We'll cover the following

The make command

The make command is an automation tool aimed at creating builds for software. It’s commonly used to compile and install software. Package managers often don’t have the latest version of a particular piece of software available, so the only way to install the most recent version is to download the source code and compile it ourselves. The process usually involves downloading the source code archive, extracting it, switching to the directory containing the code, running a script called configure to set some variables based on our environment, and running make to compile the software. It usually looks something like this:

$ ./configure
$ make
$ sudo make install

The make command works by reading a file named Makefile and looking for tasks to run. We create these tasks by defining rules that tell make what commands to run to produce the desired result. Most of the time, we define rules by specifying files we want to create. These are called targets.

Here’s an example of a rule:

%.class : %.java javac $<

This rule compiles a Java class from a source file. To run this, we type make Hello.class. Then, make would look for a file named Hello.java The $< variable represents the input file.

Here’s another example:

book.md:
         cat chapter1.md chapter2.md chapter3.md chapter4.md > $@

This rule describes making a file named book.md by concatenating four Markdown files. The $@ variable in this rule references the name of the output file. To run it, we type make book.md.

We can use Makefiles to automate all sorts of tasks. To explore how Makefiles work, we’ll create a very basic static site generator. We’ll have files containing a generic header and a footer that we’ll use on all of our pages. Then, we’ll have some files that contain just the content we want to use. Our Makefile will let us take the content and apply the template, creating a full HTML page. And for completeness, we’ll add a rule that builds all of the pages for the site. The directory structure for the project will look like this:

Get hands-on with 1200+ tech skills courses.