Unable to force drop Postgres database
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();