Passing PostgreSQL Passwords in Bash Scripts

Bash and PostgreSQL is a powerful combo, but you don’t want to be slowed down with


prompts in the terminal.

Create PostgreSQL User and Database for Linux Account

We first want to create a PostgreSQL User and Database for our Linux User Name. Besides simplifying our PostgreSQL scripts that are run under our name we can do this:

Here are the commands to create our PostgreSQL user and database.

$ sudo -u postgres createuser --superuser $USER
$ sudo -u postgres psql
postgres=# \password $USER
$ sudo -u postgres createdb $USER

If you get an error when using the $USER environment variable, simply use your username.

.pgpass and a Bonus Tip

Next we want to create our .pgpass file in the home directory. Here’s what mine looks like, with “mypassword” replacing the actual passwords.

Here’s a bonus tip for you, include both localhost and in .pgpass. If you have everything configured correctly and are still getting password prompts in your bash scripts, this might be the fix you were looking for.