Jeroen De Dauw
Jeroen De Dauw

Reputation: 10908

Defaulting an environment variable in a makefile

I have a makefile in which I want some default behavior that can be changed via an ENV var.

This works fine:

foo:
    echo "${MY_VAR}

However when a try to add the default, things stop working:

foo:
    echo "${MY_VAR:-defaultValue}"

This always echo's an empty string. If I execute the echo directly on my shell it works as expected, and I get either the value of MY_VAR, or defaultValue, depending on if MY_VAR was set.

I remember having problems in Makefiles before. Do they have some "special bash rules"?

Upvotes: 0

Views: 901

Answers (1)

MadScientist
MadScientist

Reputation: 100866

There are no special bash rules.

However, there is a big difference between make variables and shell variables.

Make variables (set in the makefile) are referenced by $(FOO) or ${FOO}. Make variables don't support shell composing operations like :-.

Shell variables are $FOO or ${FOO}, but because that syntax overlaps with make's variable syntax you have to escape them so that make doesn't mess with them. You do that by doubling the $, so to access a shell variable from within a makefile recipe you write $$FOO or $${FOO}.

You haven't made clear in your example whether MY_VAR is a make variable or a shell variable so we can't give you a solution.

Upvotes: 2

Related Questions