Search code examples
shellmakefile

Reading User Input in a Makefile Script


I have a very simple Makefile (that just recursively calls another subdirectory make):

all:
    cd addons/godot-haskell-plugin && make && cd -
run:
    cd addons/godot-haskell-plugin && make run && cd -

What I'd like to do is

  1. Check if shell variable ENV_VAR is defined.
  2. If it is, then run the Makefile as usual (i.e., ENV_VAR=1 make all should do exactly as make all above).
  3. If it isn't, then prompt the user with a message "Warning: ENV_VAR isn't defined; continue? [Y/n]", where an input of "Y" passes make all and make run as usual, and an input of "n" simply echos a message and exits.

I know that to do this in bash you would use a combination of echo and read functions. But it's unclear how to do this in Make.


Solution

  • Make isn't really intended to be interactive, but you can kludge it.

    There's more than one way to do it, but since you seem to want this behavior to be specific to some targets (all and run), I'd add a PHONY target that interacts with the user and perhaps aborts Make:

    all run: check
    
    .PHONY: check
    check:
    ifndef ENV_VAR
        @echo Warning: ENV_VAR isn\'t defined\; continue? [Y/n]
        @read line; if [ $$line = "n" ]; then echo aborting; exit 1 ; fi
    endif
    

    Note that I'm using a Make conditional for one variable, and a bash conditional for the other. You can use either for either, but in this case this is the cleanest way.