如何在postgresql中列出rolename拥有的数据库

时间:2014-09-05 17:43:26

标签: bash postgresql psql

我在root中执行bash尝试的代码。

#!/bin/bash
su - postgres <<EOF1 
F="$(psql -d postgres --tuples-only -P format=unaligned -c "SELECT datname FROM pg_database JOIN pg_authid ON pg_database.datdba = pg_authid.oid WHERE rolname = 'username'")"
EOF1 
echo $F

它输出为 错误:关系pg_authid

的权限被拒绝

但是当我尝试

su - postgres <<EOF1 
psql -d postgres --tuples-only -P format=unaligned -c "SELECT datname FROM pg_database JOIN pg_authid ON pg_database.datdba = pg_authid.oid WHERE rolname = 'username'"
EOF1 

这将打印该用户名的所有数据库。为什么这样?

我需要将输出存储到bash变量中以便进一步处理。

是否有任何错误或其他方式尝试这一点..

感谢。

1 个答案:

答案 0 :(得分:1)

内部$(...)表达式在su部分之前执行,因此它不会作为postgres运行,而是作为当前用户运行。这可能写得更好:

command="psql -d postgres --tuples-only -P format=unaligned -c \"SELECT datname FROM pg_database JOIN pg_authid ON pg_database.datdba = pg_authid.oid WHERE rolname = 'username'\""
F=$( su - postgres -c "$command" )

你可以把它们放在一起,但是:

F=$( su - postgres -c "psql -d postgres --tuples-only -P format=unaligned -c \"SELECT datname FROM pg_database JOIN pg_authid ON pg_database.datdba = pg_authid.oid WHERE rolname = 'username'\"" )

我还应该注意,第一个失败的示例可能不会将F设置为您在su之外可以阅读的任何内容。但是,Ubuntu和我认为其他现代Linux系统不允许您以这种方式使用su。您应该使用sudo -l -u postrges并适当配置/etc/sudoers,以便人们有权psqlpostgres用户运行。