Comfortably Call make from Subfolders

Building a project completely can be as simple as calling make in the project root folder, if there is a sufficiently carefully composed Makefile present. In this case, make will build the first target in the Makefile.

If we are in a sub-folder, however, make will not automatically search for Makefiles in parent folders. I’ve written a small wrapper script named mk, that simply does that:

#!/bin/bash
#
# Search Makefiles recursively and run make(1) there, if one is found
#

DEPTH="$(pwd | tr -c -d / | wc -c)"
MOD=.
NPD="--no-print-directory"

if [[ "$*" == *"-w"* || "$*" == *"--print-directory"* ]]; then
NPD=
fi

while [[ $DEPTH -gt 0 ]]; do
if [[ -f $MOD/Makefile ]]; then
if [[ $MOD == "." ]]; then
make "$@"
else
echo "make -C $MOD $*"
make $NPD -C $MOD "$@"
fi
exit 0
fi
MOD=$MOD/..
(( DEPTH-- )) || true
done

echo "No Makefile found." >&2
exit 1

This script searches upwards, starting with the current directory, and calls make, if it finds a Makefile:

$ mk
No Makefile found.
$ echo 'all:' > Makefile
$ mk
make: Nothing to be done for 'all'.
$ mkdir subfolder && cd subfolder
$ mk
make -C ./..
make: Nothing to be done for 'all'.

I conditioned myself to use mk consistently, which allows me to run the build tool from within vim with a quick :!mk, that searches Makefiles starting with the folder of the currently edited file. An additional advantage is, that we save 50% of keystrokes, when we want to call make.

You can download the script here.