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
⭐ Must Read: serhatteker/get environment variables from a file into makefile ml - ประเด็นร้อน ⭐ Must Read: serhatteker/get environment variables from a file into makefile ml - ประเด็นร้อน

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

# Makefile

include .$(PWD)/.env

dummy-target:
    @echo $(SOME_ENV_VAR)
⭐ Must Read: serhatteker/get environment variables from a file into makefile ml - ประเด็นร้อน ⭐ Must Read: serhatteker/get environment variables from a file into makefile ml - ประเด็นร้อน

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
⭐ Must Read: serhatteker/get environment variables from a file into makefile ml - ประเด็นร้อน ⭐ Must Read: serhatteker/get environment variables from a file into makefile ml - ประเด็นร้อน

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
⭐ Must Read: serhatteker/get environment variables from a file into makefile ml - ประเด็นร้อน ⭐ Must Read: serhatteker/get environment variables from a file into makefile ml - ประเด็นร้อน

All done.

Top comments (1)

⭐ Must Read: serhatteker/get environment variables from a file into makefile ml - ประเด็นร้อน
 
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