bash - 使用 bash 脚本删除 postgresql 中的所有表

标签 bash postgresql

我是 bash 脚本的新手。我正在尝试执行此 postgresql 命令(它输出删除名称类似于 r_395 的表的命令)

SELECT 'DROP TABLE ' || tablename FROM pg_catalog.pg_tables where tablename like 'r_395%';

这个查询的输出是:

?column?      
--------------------
 DROP TABLE r_395_0
 DROP TABLE r_395_1
 DROP TABLE r_395_2
 DROP TABLE r_395_3
 DROP TABLE r_395_4
 DROP TABLE r_395_5
 DROP TABLE r_395_6
 DROP TABLE r_395_7
 DROP TABLE r_395_8
 DROP TABLE r_395_9
(10 rows)

通过以下命令使用 bash:

/bin/su - postgres -c "/usr/bin/psql database -c SELECT 'DROP TABLE ' || tablename FROM pg_catalog.pg_tables where tablename like 'r_395%'" > droptables

但是我收到了这个错误:

psql: FATAL:  role "DROP TABLE " does not exist
-bash: tablename: command not found

我做错了什么?

最佳答案

可能是由于在您包含 -c 时引号被重新解释。你需要这样的东西:

su - postgres -c "/usr/bin/psql database -c \"SELECT 'DROP TABLE ' || ....

即您需要再次将 arg 引用到 psql 的 -c 选项。

这很快就会变成一团糟。我建议您改为获取您希望 psql 执行的命令作为输出生成,然后让 psql 执行 stdin(根本不传递 -c)。这避免了引用 hell ,并使测试更容易(只需取出 psql 的管道,您就会看到它会得到什么)。即:

echo "SELECT 'DROP TABLE ' || tablename ... " | su - postgres -c "psql database"

或使用“此处文档”:

su - postgres -c "psql database" <<EOF
SELECT 'DROP TABLE ' || tablename ...
EOF

关于bash - 使用 bash 脚本删除 postgresql 中的所有表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7765349/

相关文章:

bash - 为什么仅当命令位于变量中时才会出现 “Can' t find string terminator” 错误?

linux - bash cron 羊群 screen

performance - 具有许多子选择的 INSERT - 性能和错误选择性

sql-server - 在链接服务器上使用 PowerBI DirectQuery?

bash - 使用 SED 或 AWK 获取 RHEL 版本的一位整数

mysql - Bash mysql数组没有得到空值

postgresql - Heroku pgbackups :restore: an error occurred and your restore did not finish

Postgresql如何从一个表中选择仅在另一个表中可用的列中的值?

linux - 在没有父进程终止的情况下处理 SIGHUP 信号并将其传播到子进程

C# - PostgreSQL (NpgSql) bytea 数据传输进度