How to pass variables to Makefiles

Passing variables, exported variables, or .env (dot env) file variables from outside of a Makefile can be completed in a few ways.

Pass variables to Makefile using environment variables

Exported environment variables are referenced by name in the Makefile:

1
2
test:
	@echo $(TEST)
1
2
export TEST=value
make test

Output:

1
value

Pass variables to Makefile using command line

Similarly, variables may be explicitly passed to make prior to command executions.

1
2
test:
	@echo $(TEST)
1
TEST=value make test

Output:

1
value

Pass variables using .env (dot env) files

Makefiles can contain an include directive which reads one or more files before executing.

1
2
3
4
5
6
7
ifneq (,$(wildcard ./.env))
	include .env
	export
endif

test:
	@echo $(TEST)

.env file:

1
TEST=dotenv

Output:

1
dotenv