Unable to force drop Postgres database I'm trying to forcibly drop a PostgreSQL 9.4.4 database from a Bash script using psql:

#!/bin/bash
db="mydb"
psql -d $db -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '$db';"


I'm using the solution shown in this question but it doesn't work. What I see is this:


FATAL: terminating connectoin due to administrator command
server closed the connection unexpectedly
         This probably means the server terminated abnormally
         before or while processing the request.



What am I doing wrong? I own the database and my user role has the "Superuser" attribute as shown when I do \du from the Postgres console.
You are killing your own connection with that statement. You need to add and pid &lt;&gt; pg_backend_pid() to exclude the session where you run that statement:

SELECT pg_terminate_backend(pid) 
FROM pg_stat_activity 
WHERE datname = '$db'
  and pid &lt;&gt; pg_backend_pid();