red888
red888

Reputation: 31560

use environment variable if set otherwise use default value in makefile

I can do this:

MY_VAR:=$(myvar)

But what I want is to also define a value for MY_VAR that is used if the environment variable myvar isn't defined. Is this possible?

Something like:

# pseudo code
MY_VAR:=if not $(myvar) then someDefaultValue

Upvotes: 16

Views: 13788

Answers (2)

akd
akd

Reputation: 9

you can try this code below.

MY_VAR=${HOSTNAME1}
if [ "$MY_VAR" = "" ]; then
MY_VAR="DEFAULT"
fi

Upvotes: 0

Mike Kinghan
Mike Kinghan

Reputation: 61337

Assuming make is GNU Make, all the environment variable settings inherited by make are automatically registered as make variable settings. See 6.10 Variables from the Environment. So you can just write, e.g.

Makefile (1)

ifdef myvar
MYVAR := $(myvar)
else
MYVAR := default
endif

.PHONY: all

all:
    echo $(MYVAR)

Which runs like:

$ make
echo default
default

when myvar is not defined in the environment; and when it is defined, runs like:

$ export myvar=notDefault
$ make
echo notDefault
notDefault

And in case the environment variable and the make variable are the same - and why not? - it is simpler still.

Makefile (2)

MYVAR ?= default

.PHONY: all

all:
    echo $(MYVAR)

See 6.5 Setting Variables

Then:

$ make
echo default
default
$ export MYVAR=notDefault
$ make
echo notDefault
notDefault

Upvotes: 33

Related Questions