我有一個用例,我需要在規則中多次運行相同的命令。但是,命令引數需要根據另一個命令的回傳值進行更改。我發現可以$(call foo_exec)從規則中呼叫宏,這很棒。但是,請考慮以下簡化代碼:
define foo_exec
@echo $(if $(filter sylvester,$(shell cat cats.txt)),Found Sylvester!,No Sylvester found!)
endef
build:
$(call foo_exec)
@echo sylvester > cats.txt
$(call foo_exec)
如果我運行make build,我會得到以下輸出:
cat: cats.txt: No such file or directory
cat: cats.txt: No such file or directory
No Sylvester found!
No Sylvester found!
它肯定會寫cats.txt,但是,不知何故,在創建該檔案之前,宏似乎只被評估一次。
此外,在我的真實代碼中,在該宏中創建變數會很有好處,但我似乎也無法完成這項作業。以下代碼:
define foo_exec
MESSAGE := $(if $(filter sylvester,$(shell cat cats.txt)),Found Sylvester!,No Sylvester found!)
@echo $(MESSAGE)
endef
build:
$(call foo_exec)
@echo sylvester > cats.txt
$(call foo_exec)
產生這個輸出:
cat: cats.txt: No such file or directory
cat: cats.txt: No such file or directory
MESSAGE := No Sylvester found!
/bin/sh: MESSAGE: command not found
make: *** [build] Error 127
在這一點上,我開始覺得宏可能不是實作所需功能的正確方法,但我不確定如何去做并避免重復大量代碼。歡迎任何建議!
uj5u.com熱心網友回復:
以下作品
define foo_exec
@if egrep -s -q sylvester cats.txt; then echo "Found Sylvester"; else echo "No Sylvester found!"; fi
endef
build:
$(call foo_exec)
@echo sylvester > cats.txt
$(call foo_exec)
有了這個輸出:
$ make build
No Sylvester found!
Found Sylvester
問題是宏在build配方開始時被擴展。因此,我們不希望宏擴展檢查cats.txt檔案的存在。相反,我們希望宏生成將進行檢查的 bash 代碼
我可能沒有很好地解釋它!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/359466.html
下一篇:在多個專案上迭代類似的命令
