Initialize, Start Server and Create Database in Single Script I am writing a provision script for a dev environment with the following:

sudo su - postgres &lt;&lt;EOF
cd ~/data
pg_ctl -D . initdb
pg_ctl -D . -l run.log start
createdb mydb
pg_ctl -D . stop
EOF


It fails with the following error:

createdb: could not connect to database template1: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/run/postgresql/.s.PGSQL.5432"?


Manually executing the commands works. I have noticed that when createdb succeeds, there are several postgres processes, often 5 or 6, so I added the following:

...
pg_ctl -D . -l run.log start
until [ `pgrep -c postgres` -gt 4 ]; do true; done
createdb mydb
...


But it hangs, meaning pgrep never gets over 5 counts inside the script runtime. I have also tried using a subshell:

...
(pg_ctl -D . -l run.log start)
wait
createdb mydb
...


With no success.
Try adding the "-w" flag to your pg_ctl -D . -l run.log start command, so that pg_ctl should only return once the server is up. If that worked, the problem was that your createdb command was running too quickly after pg_ctl, before Postgres was actually up and accepting connections, when those commands were executed in a script as opposed to manually.

(Re-posting comment as an answer, as requested.)