Romain Lespinasse

Makefile: Ensuring Essential Variables with Validation Checks

Posted on 1 min

Makefile Tips

When you use a variable in a Makefile task and you want to make it mandatory and check it before run the effective task,

You can guard it

task-who-need-SPECIFIC_ENVVAR: guard-SPECIFIC_ENVVAR
	@echo ${SPECIFIC_ENVVAR}

You only need to add the following task

guard-%:
	@ if [ "${${*}}" = "" ]; then \
		echo "Environment variable $* not set"; \
		exit 1; \
	fi

So when you run it, the guard will prevent to run the task

$ make task-who-need-SPECIFIC_ENVVAR
Environment variable SPECIFIC_ENVVAR not set
make: *** [guard-SPECIFIC_ENVVAR] Error 1
$ export SPECIFIC_ENVVAR=value
$ make task-who-need-SPECIFIC_ENVVAR
value

See https://stackoverflow.com/a/7367903/1848685