How do I load and export variables from a .env file to a Makefile?

What is the best way to use it .env

in a Makefile i.e. loading this file and exporting all variables for subshells in make

?

It would be great if the proposed solution only works with make

eg. without using third-party tools. In addition, files .env

support multi-line variables like:

FOO="this\nis\na\nmultiline\nvar"

This is why this solution is probably not adequate.

+3


source to share


1 answer


Make does not offer any way to read the contents of a file by any variable. Therefore, I consider it impossible to achieve a result without using external tools. However, if I am wrong, I would be happy to learn a new trick.

So let's say there are two files that .env

are technically valid shell files:

FOO=bar

BAR="notfoo" # comment
   #comment
MULTILINE="This\nis\nSparta!"
# comment

      

and script.sh

:

#!/bin/bash
echo FOO=${FOO}
echo BAR=${BAR}
echo -e ${MULTILINE}

      

One solution is to include the file .env

, then make sure the variables are exported:

include .env

$(eval export $(shell sed -ne 's/ *#.*$//; /./ s/=.*$$// p' .env))

all:
    ./script.sh

      

Because of the different shell and make handling of quotation marks, you will see quotation marks in the output.



You can avoid this by redesigning the make variables:

include .env

VARS:=$(shell sed -ne 's/ *\#.*$$//; /./ s/=.*$$// p' .env )
$(foreach v,$(VARS),$(eval $(shell echo export $(v)="$($(v))")))

all:
    ./script.sh

      

but then the multi-line variable becomes a one-line variable.

Finally, you can create a temporary file to be processed by bash and reference it before running any command:

SHELL=bash

all: .env-export
    . .env-export && ./script.sh

.env-export: .env
    sed -ne '/^export / {p;d}; /.*=/ s/^/export / p' .env > .env-export

      

Oh, newlines in this case are tangled up in a multi-line variable. You must specify them additionally.

Finally, you can add export

to .env using command sed

and follow these steps:

SHELL=bash
%: .env-export
    . .env-export && make -f secondary "$@"

      

+2


source







All Articles