user2588083
user2588083

Reputation: 31

Makefile variable scope inside if/else

I am new to Makefile and I am trying to figure out two issues in the make file. Below are the details of the issue. This works when I use the shell script.

Issue1: In the below script the if condition is evaluated as true even though the account is not provided as input

Issue2: Not able to get the account and enviroment value in side if/else condition

plan:
    read -p "Account:" account && \
    read -p "Environment: " enviroment; \
    accountenv=''
    if [ -z $$account ]; then \
        echo "inside if. enviroment = $$enviroment"; \
        accountenv="$$enviroment-company"; \
    else \
        echo "inside else. enviroment = $$enviroment and account = $$account"; \
        accountenv="$$account-$$enviroment-company  "; \
    fi && \
    echo "accountenv is $$accountenv";

Input1:

Account:l
Environment: l

Output:

inside if. enviroment =
accountenv is -company

Input2:

Account:
Environment: l

Output:

inside if. enviroment =
accountenv is -company

Upvotes: 1

Views: 585

Answers (2)

Andreas
Andreas

Reputation: 5301

GNU Make provides special target ONESHELL: that makes all commands for any recipe to run in the same shell, which allows variables to be written to in one command and expanded in another.

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

However, only the return status of the last command of the recipe will determine recipe success:

...normally if any line in the recipe fails, that causes the rule to fail and no more recipe lines are processed. Under .ONESHELL a failure of any but the final recipe line will not be noticed by make.

Putting multi-line recipes in a shell script can be more convenient. Pick your poison.

Upvotes: 1

choroba
choroba

Reputation: 242218

In a Makefile, each line is run in a different shell. If you want a variable to keep its value, you need to put everything on the same line, or use backslashes.

This line

accountenv=''

has no backslash at the end, so the next line will run in a new shell. The variables populated in the previous lines won't keep their values.

Upvotes: 1

Related Questions