DEV Community

loading...

How to check a mandatory variable in a Makefile

rlespinasse profile image Romain Lespinasse Updated on ・1 min read

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

Discussion

pic
Editor guide