DEV Community

Romain Lespinasse
Romain Lespinasse

Posted on • Edited on

3

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay