我在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
至少有两个考虑因素。 qazxsw poi引用了一个Make变量。你必须逃脱qazxsw poi来做命令替换。此外,shell命令必须全部在一行上。尝试:
$()
另一方面,似乎总是尝试删除数据库并允许失败更简单:
$
在动态生成规则中使用必须使用$$$$转义shell变量。
MY_LIBS = a b c
a_objs = a1.o a2.o b_objs = b1.o b2.o b3.o c_objs = c1.o c2.o c4o
默认值:libs
#function lib_rule(name,objs)
定义lib_rule lib $(1).a:$(2)
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
exit 1 | tee make.log; test $$$$ {PIPESTATUS [0]} -eq 0 endef#generate规则 $(foreach L,$(MY_LIBS),$(eval $(调用lib_rule,$(L),$($(L)_objs))))
#call生成的规则 libs:$(patsubst%,lib%.a,$(MY_LIBS))
#dummy object generation %的.o:%C
rebuilddb: -dropdb the_db # Leading - instructs make to not abort on error createdb -E UTF8 the_db
touch $ @#dummy source generation %。C:
touch $ @
清洁::
rm -f * .c * .o lib * .a make.log
输出:'make -Rr'
退出1 | tee make.log;测试$ {PIPESTATUS [0]} -eq 0 make:*** [Makefile:18:liba.a]错误1
管道中最后一个命令的结果从tee开始。您可以看到bash变量PIPESTATUS [0]在退出1时的值为false
观看数据库:'make -Rrp'
定义lib_rule lib $(1).a:$(2)
exit 1 | tee make.log; test $$$$ {PIPESTATUS [0]} -eq 0 endef
...
libc.a:c1.o c2.o c3.o c4.o
exit 1 | tee make.log; test $$ {PIPESTATUS [0]} -eq 0