使用 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
我做错了什么?
I am a novice bash script user. I am trying to execute this postgresql command (which outputs commands that drops tables whose name is like r_395)
SELECT 'DROP TABLE ' || tablename FROM pg_catalog.pg_tables where tablename like 'r_395%';
output of this query is:
?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)
using bash with this command:
/bin/su - postgres -c "/usr/bin/psql database -c SELECT 'DROP TABLE ' || tablename FROM pg_catalog.pg_tables where tablename like 'r_395%'" > droptables
But I am getting this error:
psql: FATAL: role "DROP TABLE " does not exist
-bash: tablename: command not found
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可能是由于引号被重新解释,因为您包含了 -c。您需要类似的东西:
即您需要再次引用 psql 的 -c 选项的参数。
这很快就会变得一团糟。我建议您改为获取希望 psql 执行的命令作为输出生成,然后让 psql 执行 stdin (根本不传递 -c )。这避免了引用地狱,并使测试更容易(只需取出 psql 的管道,您就会看到它将得到什么)。即:
或使用“此处文档”:
Probably due to the quotes being reinterpreted as you're including a -c. You need something like:
i.e. you need to quote the arg to psql's -c option again.
This rapidly turns into a mess. I suggest you instead get the command you want psql to execute produced as output and then just have psql execute stdin (by not passing -c at all). This avoids the quoting hell, and makes testing easier (just take out the pipe to psql and you see what it will be getting). That is:
or use a "here document":