debug bash snippet in a makefile

First of all I have to confess: I like Makefiles! I am no make guru, but I like and use Makefiles for several tasks where it fist in my opinion.

I do not intend to write a defens manifest for Makefiles here, just wanted to describe my way to debug bash code in make targets. In general I do not want the make targets to be too noisy and just do their intended job. But in some cases, when things go wrong, I like to have the option to debug without changing to much in the Makefile itself.

You can use the make debug -d or trace options for this purpose, but this will just debug the command as seen by make.

export SHELL = /bin/bash

# silent run by default but may be turned into verbose w/
# export SILENT="" make ...
# or export SILENT="set -x;" make ...
SILENT ?= @

SUDO = $(shell [ $$(id -u) -gt 0 ] && echo sudo)

test:
    $(SILENT)if [ -z "$(SUDO)" ]; then \
            echo "skip $@ for root ($(SUDO))"; \
        else \
            RUN4USER=$$(id -un); \
            id -Gn | grep -q docker || ( sudo usermod -G docker -a $$RUN4USER; echo "you need to login again in order for the group changes will have effect"; exit 1); \
        fi
    $(SILENT)echo "$@ OK"

Now you can debug the bash code by running SILENT="set -x; " make test.


make
makefile
bash