Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Makefile: exit on conditional

Tags:

bash

makefile

I want to check that an environment variable is set before executing some code in a Makefile. If it's not set I want to throw an error with a simple error message:

run:
  [ -z "$(MY_APP)" ] && echo "MY_APP must be set" && exit 1
  echo "MY_APP is set. Yay!"
  echo "Let's continue on with the command..."

When MY_APP is not set I get the following error, which is desired:

[ -z "" ] && echo "MY_APP must be set" && exit 1
MY_APP must be set
make: *** [run] Error 1

However, when MY_APP is set I get the following error:

[ -z "EXAMPLE_NAME" ] && echo "MY_APP must be set" && exit 1
make: *** [run] Error 1

Any idea what I'm doing wrong? And is there a better way to do this?

like image 926
Johnny Metz Avatar asked Oct 29 '19 07:10

Johnny Metz


People also ask

How do you exit a Makefile?

1 Answer. You can execute a command in the shell from the Makefile by using the $(shell command) syntax. If for instance you would want to exit status of the ls command in bash you would type: ls --qwfpgjl > /dev/null 2>&1 ; echo $?

How do I use IFEQ in Makefile?

The ifeq directive begins the conditional, and specifies the condition. It contains two arguments, separated by a comma and surrounded by parentheses. Variable substitution is performed on both arguments and then they are compared.


2 Answers

Recall that the && condition require that all conditions must be TRUE to pass. Since the first condition fail, the whole command will return a status of 1 (-> false), effectively stopping the make

You can use the following, so that the test will fail only when MY_APP is missing.

Note that I'm using false instead of exit 1. Also better to use "${MY_APP}", which make it easier to copy/paste from Make to shell prompt/script.

run:
    { [ -z "$(MY_APP)" ] && echo "MY_APP must be set" && false } || true
    ...

# Or just if-Then-Else
    if [ -z "${MY_APP}" ] ; then echo "MY_APP must be set" ; false ; fi
    ...
like image 97
dash-o Avatar answered Oct 18 '22 02:10

dash-o


You can test environment variables with Makefile conditional syntax, like this:

sometarget:
ifndef MY_APP
    @echo "MY_APP environment variable missing"
    exit 1
endif

    somecommand to_run_if_my_app_is_set

Note that ifndef/ifdef operate on the name of the variable, not the variable itself.

like image 3
Geoff Williams Avatar answered Oct 18 '22 04:10

Geoff Williams