Search code examples
makefiledirectoryfile-exists

how to check if a directory exists before executing a command in a makefile


I have line like this in my makefile:

VERSION=0.7.12
SED=sed

ALL: www/Makefile

www/Makefile: Makefile
    test -d www && $(SED) -e "s/{{VERSION}}/$(VERSION)/g" www/Makefile.in > www/Makefile

the code is executing file when there is no www directory but I got message:

make: *** [www/Makefile] Błąd 1

when running make (Błąd is Polish for Error)


Solution

  • Make checks the exit code and if it's not true (not 0) then it fails. In your test you use "x && y", which means if x is not true then y is not run... but it also means the result of the expression is "not true". So make shows that error.

    In general in makefiles you only ever want to use or-expressions (||) not and-expressions:

    ! test -d www || $(SED) ...
    

    or this:

    test ! -d www || $(SED) ...
    

    Or, you can do something like:

    test -d www && $(SED) ... || true
    

    (this one always succeeds, though, even if the sed fails). Or more simply:

    if [ -d www ]; then $(SED) ... ; fi