如何在Makefile中执行子命令?我的git子命令执行异常求助
问题原因
Make会优先解析Makefile中的$()语法,将其视为Make变量引用,而非Shell的命令替换。你写的$(git describe --tags)会被Make解析为“引用名为git的Make变量,后面跟describe --tags”,但你并未定义过这个变量,所以展开后变成空字符串,最终传给Shell的命令就缺失了标签参数。
解决方案
有两种常用修复方式:
方式1:转义$符号
把Shell命令里的$换成$$,让Make将$$解析为单个$传递给Shell,由Shell执行命令替换:
build-frontend: cd frontend; printf '{"tag":"%s"}\n' $$(git describe --tags) > VERSION.json other-commands
方式2:使用Make的shell函数
如果想让Make提前执行命令(比如进入frontend目录前就获取标签),可以用Make内置的shell函数,此时git describe --tags会在Make的工作目录(项目根目录)执行:
build-frontend: cd frontend; printf '{"tag":"%s"}\n' $(shell git describe --tags) > VERSION.json other-commands
注意:这种方式和Shell直接执行的逻辑略有差异——前者在根目录执行git,后者在frontend目录执行git。如果你的git仓库根目录就是项目根目录,两种结果一致;如果frontend是子仓库,建议用第一种方式。
额外优化:如果cd frontend失败(比如目录不存在),后面的命令仍会执行,可改成用&&连接命令,确保前面成功才执行后续操作:
build-frontend: cd frontend && printf '{"tag":"%s"}\n' $$(git describe --tags) > VERSION.json other-commands
内容的提问来源于stack exchange,提问作者HubertNNN
相关产品推荐
相关产品推荐

