我是 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/