Search code examples
bashshellmakefileenvironment-variables

Define a Makefile variable using a ENV variable or a default value


I am trying to do a simple thing:

TMPDIR ?= /tmp

test:
    @echo $(TMPDIR)

This works if I run:

$ make test
/tmp

It also works if I run:

$ make test -e TMPDIR=~/tmp
/home/user/tmp

What can I do to also have it works for:

$ TMPDIR=~/tmp make test
/home/user/tmp

Solution

  • To follow up on my comments above, here's an example:

    T ?= foo
    all:
            $(info T is $(T))
    

    Now if I run the Makefile in various ways, it behaves as we expect (I get foo only if I don't set T either on the command line or environment):

    $ make
    T is foo
    
    $ make T=bar
    T is bar
    
    $ T=bar make
    T is bar