Granted the question is 9 years old at this point, but it's still the second google result for deleting all databases. If you just want to go from N DBs to 0 without jacking with your config and also having rummage through the file system, this is a much better answer:
https://stackoverflow.com/a/24548640/3499424
From the answer, the following script will generate N drop database commands, one for each non-template DB:
select 'drop database "'||datname||'";'
from pg_database
where datistemplate=false;
From there, you can edit and run manually, or pipe further along into a script. Here's a somewhat verbose one-liner:
echo \pset pager off \copy (select 'drop database "'||datname||'";' from pg_database where datistemplate=false) to STDOUT; | psql -U <user> -d postgres | <appropriate grep> | psql -U <user> -d postgres
Explanation:
- This is a series of pipes
echo \pset pager off \copy (select 'drop database "'||datname||'";' from pg_database where datistemplate=false) to STDOUT; generates a string for psql to execute
\pset pager off ensures you get all records instead of that (54 rows) crap
\copy (select 'drop database "'||datname||'";' from pg_database where datistemplate=false) to STDOUT; executes the aforementioned query, sending the result to STDOUT. We have to do this since we lead with \pset.
| psql -U <user> -d postgres pipes said string into psql, which executes it. Replace <user> with the user you want to use
| <appropriate grep> is for stripping out the "Pager usage is off" line
- Windows users can use
findstr /v "Pager" or findstr /b "drop"
- *nix users can use
grep 'drop'
| psql -U <user> -d postgres pipes the resulting set of drop database commands into psql again, which executes them, thus dropping all the databases
- WARNING: Without any additional filtering, this will also drop the
postgres database. You can strip it either in the SELECT or the grep if you don't want that to happen.