我想只有在Git是存在的git獲取當前SHA1哈希和我在一個Git倉庫
你可以做到這一點,如:
的Makefile 1
HASH := $(if $(and $(wildcard .git),$(shell which git)), \
$(shell git rev-parse HEAD))
hash:
ifdef HASH
@echo $(HASH)
@echo "#define GIT_SHA1 \"$(HASH)\"" > git_sha1.h
else
@echo "Git not installed or not in a git repository"
endif
其運行如下:
$ make
7cf328b322f7764144821fdaee170d9842218e36
在git倉庫時(與至少一個提交),並且當未在git倉庫 運行,如:
ifdef HASH
:
$ make
Git not installed or not in a git repository
參見8.4 Functions for Conditionals
通知之間的對比度
並在你自己的嘗試中:
ifdef $(GIT)
第一個測試是否爲HASH
是一個定義(即,非空)生成變量,這就是我想要的 。第二個測試是否爲$(GIT)
,即的值的GIT
,您希望它是`哪個git`, 是一個定義的make變量。這不是你想要的。 `其中git`不是限定化妝變量,即使GIT
是,和:
ifdef `which git`
將是一個錯誤的語法時才[1]。
想必你有沒有真正的需要:
@echo $(HASH)
在這種情況下,你可以簡化爲:
的Makefile 2
hash:
ifneq ($(and $(wildcard .git),$(shell which git)),)
@echo "#define GIT_SHA1 \"$$(git rev-parse HEAD)\"" > git_sha1.h
else
@echo "Git not installed or not in a git repository"
endif
[1]所以,爲什麼不你沒有看到
ifdef $(GIT)
的語法錯誤嗎?因爲
GIT
不是=`在這種情況下哪個git`。它是未定義的。下面 生成文件說明:
的Makefile 3
GLOBAL_VAR_A := global_var_a
all:
$(eval RECIPE_VAR_A=recipe_var_a)
ifdef RECIPE_VAR_A
@echo $(RECIPE_VAR_A) for RECIPE_VAR_A
else
@echo RECIPE_VAR_A is defined only within the recipe
endif
ifdef GLOBAL_VAR_A
@echo GLOBAL_VAR_A is defined globally
@echo $(RECIPE_VAR_A) for GLOBAL_VAR_A
endif
運行:
$ make
RECIPE_VAR_A is defined only within the recipe
GLOBAL_VAR_A is defined globally
recipe_var_a for GLOBAL_VAR_A
爲什麼第一個建議結果中處於領先空間中的散列字符串,因爲它出現在'git_sha1。 h'? – Frotz
@Frotz啊,這是因爲我將HASH的定義劃分爲SO格式。 (如果$(和$(通配符.git),$(shell是哪個git)),$(shell git rev-parse HEAD))' 並且不會有前導空間。 –