Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Makefile include .env conflicts with MAKEFILE_LIST

Tags:

makefile

I have a Makefile where I want to load environment variables placed in .env file.

I am using the include directive to achieve this.

-include .env

I also have an help target to display the available tasks:

help: ## Displays help menu
    grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'

The problem is that when using together with the include directive, it doesnt work correctly. The help task just shows "Makefile" as name for all the targets.

The $(MAKEFILE_LIST) returns "Makefile, .env" instead of the target names, so I guess it became messed up with the .env somehow.

I don´t know enough about Makefiles to understand what´s wrong.

Any ideas?

Thanks you.

like image 297
brpaz Avatar asked Sep 06 '25 00:09

brpaz


1 Answers

Solution

Update your help target to leverage $(firstword $(MAKEFILE_LIST)) instead of just $(MAKEFILE_LIST) so that grep is targeting the correct file before it pipes the targets with ## comments.

help: ## Displays help menu
    grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(firstword $(MAKEFILE_LIST)) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'

Explanation

The original behavior of the $MAKEFILE_LIST variable is to output Makefile rather than a list of the Makefile's that are being included. So after your include, it's appending the name to the list. So you see what you mentioned Makefile, .env. The grep command that you posted for the help target is taking $MAKEFILE_LIST and grepping .env along with Makefile. Since that pattern for comment / help messages doesn't match anything in .env there isn't any output, but the Makefile does contain matches. This leads grep to prepend the FILENAME in which it found things in. In this case, Makefile. The awk command then rips everything before ## and strips them to a : colon, which grep added and it reads that as the target rather than what the target is in your Makefile. So all your help output has the correct comment but the wrong target. You can verify the behavior by running the following grep command in the directory where both these files exist:

grep -E '^[a-zA-Z_-]+:.*?## .*$$' Makefile .env
like image 71
rogeruiz Avatar answered Sep 08 '25 00:09

rogeruiz