如何删除匹配模式的postgresql数据库?

[英]How to delete postgresql databases matching a pattern?


With pgAdmin III, I can list all the databases on my postgresql server.

使用pgAdmin III,我可以在postgresql服务器上列出所有数据库。

But with pgAdmin, I can delete only 1 database at the time. It takes a lot of time to delete, for example, 30 databases, one by one...

但是使用pgAdmin,我当时只能删除1个数据库。需要花费大量时间来删除,例如,30个数据库,一个接一个......

So, what would be your approach to delete, for example, all the databases with a name containing the word "june"?

那么,您的删除方法是什么,例如,所有名称中包含“june”一词的数据库?

Probably I will have to build a Bash script. No problem with this. But which command would you use in this script?

可能我将不得不构建一个Bash脚本。没问题。但是你会在这个脚本中使用哪个命令?

I have search the web for many hours without success for this problem...

我已经在网上搜索了好几个小时而没有成功解决这个问题......

Thanks to help.

感谢帮助。

2 个解决方案

#1


5  

psql -c "copy (select datname from pg_database where datname like '%june%') to stdout" | while read line; do
    echo "$line"
    #dropdb -i "$line"
done

Or using for loop which is more reliable (while block executed in the parent context so it is necessary to do some additional movements for its body):

或者使用更可靠的for循环(在父上下文中执行块时,因此有必要为其主体执行一些额外的移动):

for dbname in $(psql -c "copy (select datname from pg_database where datname like '%june%') to stdout") ; do
    echo "$dbname"
    #dropdb -i "$dbname"
done

Also option -X for psql (do not use ~/.psqlrc file) could be good to avoid unnecessary outputs.

另外选项-X for psql(不要使用〜/ .psqlrc文件)可以很好地避免不必要的输出。

For psql and dropdb utilities you probably need to provide the connection options (see documentation)

对于psql和dropdb实用程序,您可能需要提供连接选项(请参阅文档)

#2


1  

Big thanks to Abelisto.

非常感谢Abelisto。

Really happy to have his script!

真的很高兴有他的剧本!

Here are our last script who works well. Absolutely great! After many months of search.

这是我们最后一个运作良好的脚本。绝对棒极了!经过几个月的搜索。

#!/bin/bash
clear
export PGPASSWORD="ssadas"

PATTERN=$1

echo "Le paramètre passé est : $PATTERN"

/usr/bin/psql -U odoo -d postgres -c "copy (select datname from pg_database where datname like '%$PATTERN%') to stdout" | while read line; do
    echo "$line"
    dropdb -U odoo "$line"
done
echo
echo "Les bases de données ayant $PATTERN dans leur nom on été effacées!"
echo
exit

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2016/07/27/e2f857f8a102f590a79c2d257c7750f6.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号