如何在 makefile 中获取 shell 环境变量?

How to get a shell environment variable in a makefile?

在shell时我输入

echo $demoPath

它打印

/usr/local/demo

如何在 makefile 中获取此变量 $demoPath 的值?

如果您导出了环境变量:

export demoPath=/usr/local/demo

你可以在makefile中简单地通过名称引用它(make导入你设置的所有环境变量):

DEMOPATH = ${demoPath}    # Or $(demoPath) if you prefer.

如果您没有导出环境变量,则在导出之前无法访问它,或者除非您在命令行上明确传递它:

make DEMOPATH="${demoPath}" …

如果您使用的是 C shell 导数,请将 setenv demoPath /usr/local/demo 替换为 export 命令。

all:
    echo ${PATH}

或者只为一个命令更改 PATH:

all:
    PATH=/my/path:${PATH} cmd

对于那些想要一些官方文件来确认行为的人

Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. (If the ‘-e’ flag is specified, then values from the environment override assignments in the makefile.

https://www.gnu.org/software/make/manual/html_node/Environment.html

如果在同一脚本中导出变量,则需要使用两个 $$ 而不是 $, 如果您的 Makefile 看起来像这样:

target:
        . ./init.sh; \
        echo ${HOMEPATH}:$${FOO};

init.sh脚本中导出变量FOO

$ cat ./init.sh
#!/bin/bash
export FOO=foo:

这样,当您 运行 将在脚本 运行 之前定义的环境变量 HOMEPATH 设为目标时,将仅使用一个 $,但是在同一脚本中导出的环境变量 FOO 需要 $$ 才能显示