命令替换不适用于 makefile 中的 echo [英] command substitution doesn't work with echo in makefile
问题描述
这是一个在我的 bash shell 中运行良好的简单命令:
Here's a simple command that works fine in my bash shell:
echo "Created at: $(date)" >> README.md
它将 Created at: Wed Jan 24 10:04:48 STD 2018
附加到 README.md.
It appends Created at: Wed Jan 24 10:04:48 STD 2018
to README.md.
然而,ii 我在我的 makefile 中包含相同的命令,行为是不同的.
However, ii I include the same command in my makefile, the behavior is different.
制作文件:
README.md:
echo "Created at: $(date)" >> README.md
运行 make README.md
会将命令替换视为一个空字符串,如下所示:
Running make README.md
will treat the command substitution as an empty string like this:
echo "Created at: " >> README.md
附加到 README.md 的是 Created at:
.
What's appended to README.md is Created at:
.
如何使用 makefile 中的 echo 进行命令替换以正确输出?
How do I get command substitution to output properly with echo in a makefile?
推荐答案
如果你想让 Make 调用的 shell 收到以下内容:
If you want the shell that Make invokes to receive the following:
echo "Created at: $(date)" >> README.md
然后,您需要在规则中使用另一个 $
对 $
进行转义:
Then, you need to escape the $
with another $
inside the rule:
README.md:
echo "Created at: $$(date)" >> README.md
否则,Make 的变量 date
被扩展,这将是 echo
作为参数得到的,因为 $(date)
在 makefile 中展开变量 date
.
Otherwise, the Make's variable date
is expanded and that will be what echo
gets as argument, since $(date)
in a makefile expands the variable date
.
请注意,如果 Make 的变量 date
定义如下,它将按预期工作,而无需在规则中引用 $
:
Note that, if the Make's variable date
is defined as below, it will however work as expected without quoting the $
in the rule:
date = $$(date)
README.md:
echo "Created at: $(date)" >> README.md
原因是变量 date
(在规则的配方中使用)将被 Make 扩展为 $(date)
并将传递给 shell.
The reason is that the variable date
(used in the rule's recipe) will be expanded by Make to $(date)
and that will be passed to the shell.
这篇关于命令替换不适用于 makefile 中的 echo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!