Ank*_*ank 3 linux bash makefile gnu-make
我有一个版本文件verfile,其中包含以下版本字符串
V1.1.2
在Makefile中我打算读取这个版本的字符串,所以我写了Makefile如下,
filepath := $(PWD)
versionfile := $(filepath)/verfile
all:
cat $(versionfile)
version=$(shell cat $(versionfile))
echo "version=$(version)"
Run Code Online (Sandbox Code Playgroud)
现在,当我运行make文件时,我得到了以下输出
cat /home/ubuntu/ankur/verfile
v1.1.2
version=v1.1.2
echo "version="
version=
Run Code Online (Sandbox Code Playgroud)
所以我无法在变量中存储版本字符串并在以后使用它,我不知道我做错了什么?
有什么建议/指针吗?
在阅读了"Didier Trosset"的回答后,我改变了我的makefile,如下所示,
filepath := $(PWD)
versionfile := $(filepath)/verfile
myversion := ""
all:
ifeq ($(wildcard $(versionfile)),)
all:
echo "File not present"
else
all: myversion = $(shell cat $(versionfile))
endif
all:
echo "myversion = $(myversion)"
Run Code Online (Sandbox Code Playgroud)
以下是输出
echo "myversion = v1.1.2"
myversion = v1.1.2
Run Code Online (Sandbox Code Playgroud)
你有两个问题.首先要使用bash(而不是make)扩展你需要使用的变量$$version(或$${version}).通过这个Make首先转换$$为just $然后bash将看到$version(或${version}).其次,规则中的每一行都将作为一个单独的命令执行,所以为了让它们通过环境变量进行交互,你必须将它们放入一个公共的子shell中,用paranthesis括起来.
filepath := $(PWD)
versionfile := $(filepath)/verfile
all:
cat $(versionfile)
(version=$(shell cat $(versionfile)); echo "version=$$version")
Run Code Online (Sandbox Code Playgroud)
我通常更喜欢在make变量中使用此版本字符串.
因此,我宁愿使用以下方法将变量保存到变量中,并将规则/目标/命令保存在规则/目标/命令中.
filepath := $(PWD)
versionfile := $(filepath)/verfile
version := $(shell cat $(versionfile))
info:
echo "version=$(version)"
Run Code Online (Sandbox Code Playgroud)
请注意,这里version是一个真正的make变量.(与仅存在于目标的lingle规则行中的bash变量相反.)
如果你需要一些命令来创建versionfile它,那么最好在它自己的目标上创建这个文件
filepath := $(PWD)
versionfile := $(filepath)/verfile
all: versionfile
echo "version=$(version)"
all: version = $(shell cat $(versionfile))
versionfile:
# Create your version file here
Run Code Online (Sandbox Code Playgroud)
请注意,您不能再使用:=目标变量:它将在Makefile读取而不是在使用时读取文件,即在versionfile创建目标之后.