How to initialize a PostgreSQL database without running the PostgreSQL server
<p>In an initialization script, I want to initialize a PostgreSQL directory, but don't need (and don't want) a running PostgreSQL server at this stage.</p>

<p>This would be a no-brainer if I just create the cluster (as user <code>postgres</code>):</p>

<pre><code>initdb -D ...
</code></pre>

<p>However, I also need to create the PostgreSQL role, create the database and add some extensions  (also as user <code>postgres</code>):</p>

<pre><code>createuser someuser
createdb -O someuser somedb
echo 'CREATE EXTENSION xyz;' | psql somedb
</code></pre>

<p>The latter commands require a running PostgreSQL server. So this whole thing becomes quite messy:</p>

<pre><code>initdb -D ...

# Start PostgreSQL server in background
... &amp;

# Wait in a loop until PostgreSQL server is up and running
while ! psql -f /dev/null template1; do
    sleep 0.5
done

createuser someuser
createdb -O someuser somedb
echo 'CREATE EXTENSION xyz;' | psql somedb

# Kill PostgreSQL server
kill ...

# Wait until the process is really killed
sleep 2
</code></pre>

<p>Especially the part that is waiting for the PostgreSQL server is never 100% reliable. I tried lots of variants and each of them failed in roughly 1 of 20 runs. Also, killing that process may not be 100% reliable in a simple shell script, let alone ensuring that it has stopped correctly.</p>

<p>I believe this is a standard problem that occurs in all use cases involving bootstrapping a server or preparing a VM image. So one would expect that in the year 2016, there should be some existing, realiable tooling for that. So my questions are:</p>

<ul>
<li>Is there a simpler and more reliable way to achieve this?</li>
<li>For example, is there a way to run a PostgreSQL server in some special mode, where just starts up, executes certain SQL commands, and quits immediately after the last SQL command finished?</li>
<li>As a rough idea, is there something from the internal PostgreSQL test suite can be reused for this purpose?</li>
</ul>