#!/bin/sh -eux db="$1" owner="${2:-$db}" case $(sudo -u postgres psql template1 -t -c \ "SELECT datname FROM pg_catalog.pg_database WHERE datname = '$db' LIMIT 1" ) in (" $db") true;; (*) sudo -u postgres psql template1 -a -f - --set ON_ERROR_STOP=1 <<-EOF CREATE DATABASE $db WITH OWNER=$owner; EOF ;; esac sudo -u postgres psql template1 -a -f - --set ON_ERROR_STOP=1 <<-EOF REVOKE ALL ON DATABASE $db FROM public; EOF sudo -u postgres psql "$db" -a -f - --set ON_ERROR_STOP=1 <<-EOF GRANT ALL ON SCHEMA public TO $owner WITH GRANT OPTION; EOF