Make: 设置 shell 并同时获取一个文件?

Make: Set shell and source a file at the same time?

假设我想在make中设置一个shell:

SHELL:=/usr/bin/env bash

接下来,假设我有一些 runcom/bash 文件我也想获取。此文件可选择激活虚拟环境:

if [ -d venv ]; then source venv/bin/activate fi;

但是,如果我写:

SHELL:=/usr/bin/env bash && source runcom/bash

这失败了。但是,如果我将 venv 逻辑存入本地 ~/.bashrc 并写入:

SHELL:=/usr/bin/env bash -l

我可以获得我需要的确切功能。


但是,我必须将一些应该保留在本地用户下游的东西存放到用户的上游环境中——我宁愿不这样做。

有没有办法让 make shell 在 make 启动过程中的声明步骤中获取文件?

这行不通:

SHELL:=/usr/bin/env bash && source runcom/bash

因为SHELL告诉make如何调用shell;如果你使 SHELL 的内容成为一个 shell 脚本,那么 make 必须调用 shell 来解释如何调用 shell,这意味着它必须调用 shell 调用 shell 解释如何调用 shell,等等

因此,SHELL 必须是一个简单的命令,或者至多是一组可以转换为 argv 列表并传递给 exec(2) 的简单参数。

所以,这实际上是一个 shell 问题而不是一个 make 问题:你如何让 shell 在开始时不改变 ~/.profile 或其他任何东西来获取任意内容?

幸运的是,这是可能的;请参阅 bash 手册页:

   BASH_ENV
          If  this parameter is set when bash is executing a shell script,
          its value is interpreted as a filename  containing  commands  to
          initialize the shell, as in ~/.bashrc.  The value of BASH_ENV is
          subjected to  parameter  expansion,  command  substitution,  and
          arithmetic  expansion  before  being  interpreted as a filename.
          PATH is not used to search for the resultant filename.

   ENV    Similar to BASH_ENV; used when the shell  is  invoked  in  posix
          mode.

因此,在您的 makefile 中,您可以使用如下内容:

SHELL := /bin/bash
export BASH_ENV := runcom/bash

这应该足够了。