bash – 如何在Makefile操作中使用shell變數?
我在Makefile中有以下內容,以便重新建立我的資料庫,包括在必要時銷燬它.這是行不通的.
.PHONY: rebuilddb exists=$(psql postgres --tuples-only --no-align --command "SELECT 1 FROM pg_database WHERE datname='the_db'") if [ $(exists) -eq 1 ]; then dropdb the_db fi createdb -E UTF8 the_db
執行它會導致錯誤:
$make rebuilddb exists= if [-eq 1 ]; then /bin/sh: -c: line 1: syntax error: unexpected end of file make: *** [rebuilddb_postgres] Error 2
為什麼這是錯的?我可以告訴我看起來像有效的Bash嗎?在Makefile中執行此操作時,是否有特別的注意事項?
更新:
使用答案我到達了一個工作版本:
.PHONY: rebuilddb exists=$$(psql postgres --tuples-only --no-align --command "SELECT 1 FROM pg_database WHERE datname='the_db'"); \ if [ "$$exists" == "1" ]; then \ dropdb the_db; \ fi; createdb -E UTF8 the_db
至少有兩個考慮因素. $()引用一個Make變數.您必須逃避$才能做過程替換.此外,shell命令必須全部在一行上.嘗試:
exists=$$(psql postgres --tuples-only --no-align --command "SELECT 1 FROM \ pg_database WHERE datname='the_db'"); \ if [ "$$exists" -eq 1 ]; then \ dropdb the_db; \ fi; \ createdb -E UTF8 the_db
另一方面,似乎總是嘗試刪除資料庫並允許失敗會更簡單:
rebuilddb: -dropdb the_db# Leading - instructs make to not abort on error createdb -E UTF8 the_db
http://stackoverflow.com/questions/13774784/how-do-i-use-shell-variables-in-makefile-actions