0

I have to set the profile variable in Makefile, if it's not set by default, here is my approach.

But when I run this, echo statements work fine, but variables are not being set.

set_vars:
    if [ "${profile}" = "" ]; then \
        profile="test"; \
    else \
        echo "Profile exists";\
    fi

    echo $(profile);
1
  • 1
    Makefiles are tricky as WHITESPACE (space and tab chars) matters.
    – Hannu
    Commented Nov 12, 2022 at 9:04

1 Answer 1

4

You need to remember that the "makefile" part of make, is separate from the "shell" part.

Once you're inside the recipe for the makefile it's all shell commands. That means you can't set a makefile variable from within it.

There are ways to get around this however, using the $(shell) and $(eval) makefile commands.

https://www.gnu.org/software/make/manual/html_node/Shell-Function.html

https://www.gnu.org/software/make/manual/html_node/Eval-Function.html

In your case something like this could work. The eval command evaluates the remaining text AS makefile (even when inside a recipe), so we set the Makefile variable profile to the result of a shell command. In there, you can make your bash assertions and echo out whatever you want the variable to be.

Only then will your change to the makefile variable actually occur.

set_vars:
    $(eval profile := $(shell [ "${profile}" = "" ] && echo 'test' || echo 'Profile Exists')

    echo $(profile);

On the other hand, you could instead, convert your Makefile variable to a bash variable and manipulate it that way:

set_vars:
    PROFILE=${profile}
    if [ $PROFILE = "" ]; then \
        PROFILE="test"; \
    else \
        echo "Profile exists";\
    fi

    echo $PROFILE;

Hope this helps!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .