Home > bash > Reading environment variables from a file into a Makefile

Reading environment variables from a file into a Makefile

Problem:
You have a bunch of environment variables that are explicitly set at the beginning of a Makefile. These variables are then used in various recipes in the Makefile. The issue was that when a developer runs the Makefile, these environment variables overwrite their local settings.

Solution:
One option is to move the environment variables out of the Makefile and use include to add them back. So the developer can use whatever values they have in their current setup as long as the names are the same.

# Makefile

foo=FOO1
bar=BAR1
baz=BAZ1

export foo
export bar
export baz

.PHONY:  target1 target2 target3

target1:
    @echo $(foo)

target2:
    @echo $(bar)

target3:
    @echo $(baz)

After splitting it up.

# .env file
foo=FOO1
bar=BAR1
baz=BAZ1

export foo
export bar
export baz
# Makefile
include .env

.PHONY:  target1 target2 target3

target1:
    @echo $(foo)

target2:
    @echo $(bar)

target3:
    @echo $(baz)

The problem with this approach is that the .env file needs to exist everywhere it will run. If you have some CI/CD setup that may not be the case. Instead have the Makefile as below and have the ENV vars set up the usual way you would in your CI/CD setup. On the local machine one can simply run $ source .env before running $ make to get things to work.

# Makefile
.PHONY:  target1 target2 target3

target1:
    @echo $(foo)

target2:
    @echo $(bar)

target3:
    @echo $(baz)

Source:
https://stackoverflow.com/questions/39005789/reading-makefile-variables-from-bash-script

Categories: bash Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: