DEV Community

Romain Lespinasse
Romain Lespinasse

Posted on • Updated on

How to check a mandatory variable in a Makefile

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}
Enter fullscreen mode Exit fullscreen mode

You only need to add the following task

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

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
Enter fullscreen mode Exit fullscreen mode
$ export SPECIFIC_ENVVAR=value
$ make task-who-need-SPECIFIC_ENVVAR
value
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)