DEV Community

Serhat Teker
Serhat Teker

Posted on • Originally published at tech.serhatteker.com on

Get Environment Variables From a File into Makefile

It is very easy to achive that in make:

# Makefile  include .$(PWD)/.env 
Enter fullscreen mode Exit fullscreen mode

That's all. You can now access your env vars in make targets:

# Makefile  include .$(PWD)/.env dummy-target: @echo $(SOME_ENV_VAR) 
Enter fullscreen mode Exit fullscreen mode

Sub-make

If want to you pass all your environment variables into Sub-make you should export them:

# Makefile  ENV := $(PWD)/.env # Environment variables for project include $(ENV) # Export all variable to sub-make export 
Enter fullscreen mode Exit fullscreen mode

Multiple Files

You can use multiple env files and their names can be anything:

# Variables # ------------------------------------------------------------------------------------- VENV := $(PWD)/.venv ENV := $(PWD)/.env ENVS := $(PWD)/.envs # Environment variables for project include $(ENV) # Local environment variables for db include $(ENVS)/.postgres include $(ENVS)/.redis # Export all variable to sub-make export 
Enter fullscreen mode Exit fullscreen mode

All done.

Top comments (1)

Collapse
 
smac89 profile image
smac89

Downside to this is that .env syntax is not a subset of the Makefile syntax because there are certain symbols allowed in .env, which make requires to be escaped. For example the symbols: # and $.

Also the fact that make treats tab as special means that it will attempt to interpret tabs as meaningful inside .env files