With pgAdmin III, I can list all the databases on my postgresql server.
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...
So, what would be your approach to delete, for example, all the databases with a name containing the word "june"?
Probably I will have to build a Bash script. No problem with this. But which command would you use in this script?
I have search the web for many hours without success for this problem...
Thanks to help.
Using the option -f or –force with dropdb command or FORCE with DROP DATABASE to drop the database, it will terminate all existing connections with the database. Similarly, DROP DATABASE FORCE will do the same. In the first terminal, create a test database and a database test, and connect to the database.
Using memory purge configuration parameters, Postgres Pro Standard can automatically replace data with zero bytes before it is deleted. This section describes how different types of data are handled. By default, all the memory purge parameters are switched on.
Unix. The default directory for PostgreSQL is /usr/local/pgsql. To uninstall PostgreSQL, manually delete the PostgreSQL folder from the default directory. To delete the database files, manually delete the Data folder from the default directory.
Use the TRUNCATE TABLE command.
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 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.
For psql
and dropdb
utilities you probably need to provide the connection options (see documentation)
Big thanks to Abelisto.
Here are our last script that works well, after many months of search.
#!/bin/bash
clear
export PGPASSWORD="xxxxx"
PATTERN=$1
echo "Pattern parameter: $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 xxxx "$line"
done
echo
echo "Databases which names matches pattern $PATTERN were deleted!"
echo
exit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With