bash – 如何在Makefile操作中使用shell变量?

前端之家收集整理的这篇文章主要介绍了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
原文链接:https://www.f2er.com/bash/386700.html

猜你在找的Bash相关文章