Use Makefiles to quickly run common commands

A tip I picked up from work is the use of a Makefile to set up short aliases for commands you run often, but that are a pain to type, or you can’t remember. I find this particularly useful as I code fairly intermittently these days, so it’s easy to forget the exact syntax of certain commands.

A good example is how to run unit tests. This varies from project to project, but is something you’ll probably want to do fairly often.

To start, create a blank file called “Makefile” and put it at the root of your project. Then insert the following code:

SHELL:=/bin/bash

unit-test:
[TAB]./vendor/bin/phpunit

Change /bin/bash to the location of Bash, and modify the ./vendor/bin/phpunit line to do whatever you’d normally type in to run your unit tests.

You’ll need to replace [TAB] with a Tab character. Spaces won’t work. Make is strict in this regard.

Save and exit the file. Now open a Terminal, go to the root of your project, and type:

$ make unit-test

All being well, this will run your unit tests.

In the Makefile, “unit-test:” indicates the label you’ll need to run after “make” to run the command. You can add multiple lines and multiple labels – for instance:

echo-ab:
[TAB]echo 'A'
[TAB]echo 'B'

echo-cd:
[TAB]echo 'C'
[TAB]echo 'D'

If you have lots of commands, this method can get a bit messy. It’s handy for small projects where you only have a few things to include but can’t always remember them.

Leave a comment