【问题标题】:Load .env file in Makefile在 Makefile 中加载 .env 文件
【发布时间】:2015-05-18 10:30:36
【问题描述】:

有没有一种简单的方法可以将包含本地配置的文件自动加载到Makefile 中?

我有一个文件 .env,每行包含 key=value 对:

var1=val1
var2=val2

目前我将每个变量手动导入到我的Makefile 中,如下所示:

  var1=$$(grep '^var1=' .env | cut -d= -f2-)

当添加更多变量时,这感觉很笨拙并且容易出现错误。

我还尝试向Makefile 添加一个额外的目标以读取.env 的每一行并将其传递给export,但是在一个目标中导出的值对其他人不可用。

我希望 make 中有一个内置功能可以执行此操作,但我无法找到它的文档。

【问题讨论】:

  • include 不是在这里做你想做的事吗?这些值是否都需要专门导出到运行的进程?
  • @EtanReisner 是的,包括完美的作品 - 谢谢!我可能应该在文档中找到它!将此添加为答案,我很乐意接受。
  • 来自the docsOne occasion for using include directives is when several programs, handled by individual makefiles in various directories, need to use a common set of variable definitions (see Setting Variables) or pattern rules (see Defining and Redefining Pattern Rules).

标签: makefile


【解决方案1】:

假设您的包含文件完全由有效的 make 分配组成,那么 include directive 可能就是您想要的。

include 指令告诉 make 暂停读取当前的 makefile 并在继续之前读取一个或多个其他 makefile。该指令是 makefile 中的一行,如下所示:

include filenames…

文件名可以包含 shell 文件名模式。

【讨论】:

  • 该 include 最好用 ifneq (,$(wildcard ./.env)) 包装,因为如果文件不存在,仅使用 include filename 会引发错误,并且我们可能有一些 env vars 的默认值。 Lithic Tech's Blog 有一篇关于它的非常好的帖子
  • 如果想在包含不存在的文件时避免出错,可以使用"""-include filename""";对于该用例,通配符本身并不真正需要。
猜你喜欢
  • 2017-11-21
  • 1970-01-01
  • 2017-06-25
  • 2018-06-05
  • 2021-04-20
  • 2020-06-19
  • 2019-02-12
  • 2021-08-29
  • 1970-01-01
相关资源
最近更新 更多