我使用以下修改的Arturo的解决scheme:
psql -lqt | cut -d \| -f 1 | grep -qw
它能做什么
psql -l输出如下所示的内容:
List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -----------+-----------+----------+------------+------------+----------------------- my_db | my_user | UTF8 | en_US.UTF8 | en_US.UTF8 | postgres | postgres | LATIN1 | en_US | en_US | template0 | postgres | LATIN1 | en_US | en_US | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | LATIN1 | en_US | en_US | =c/postgres + | | | | | postgres=CTc/postgres (4 rows)
使用简单的方法意味着search名为“List”,“Access”或“rows”的数据库将会成功,所以我们通过一堆内置的命令行工具pipe理这个输出,只在第一列进行search。
-t标志删除页眉和页脚:
my_db | my_user | UTF8 | en_US.UTF8 | en_US.UTF8 | postgres | postgres | LATIN1 | en_US | en_US | template0 | postgres | LATIN1 | en_US | en_US | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | LATIN1 | en_US | en_US | =c/postgres + | | | | | postgres=CTc/postgres
接下来的一点, cut -d \| -f 1 cut -d \| -f 1通过垂直pipe道分割输出 字符(使用反斜杠从shell中转义出来),并select字段1.这会留下:
my_db postgres template0 template1
grep -w匹配整个单词,因此如果在此scheme中searchtemp ,则不匹配。 -q选项禁止任何输出写入屏幕,所以如果你想在命令提示符下以交互方式运行这个输出,你可以用排除-q立即显示。
请注意, grep -w匹配字母数字,数字和下划线,这正是postgresql中未加引号的数据库名称中允许使用的字符集(连字符在非引号标识符中不合法)。 如果您使用其他字符,则grep -w将不适用于您。
如果数据库存在,整个pipe道的退出状态将为0 (成功),否则为1 (失败)。 你的shell将设置特殊variables$? 到最后一个命令的退出状态。 您也可以直接在条件中testing状态:
if psql -lqt | cut -d \| -f 1 | grep -qw ; then # database exists # $? is 0 else # ruh-roh # $? is 1 fi