Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In a bash script I'm writing, I need to create a database and set a password that is generated automatically by my script.

The problem is I can't find a way to set up the password without user interaction.

I need something like this:

$ createdb mydb -p $(cat password_file)

Any ideas?

share|improve this question
@ChocoDeveloper: in the case that you're thinking of a password assigned to the database itself, postgres doesn't have this. Passwords are assigned to database users which are separately granted the permission to connect to databases. – Daniel Vérité Jun 17 '13 at 21:58

From the documentation:

createdb is a wrapper around the SQL command CREATE DATABASE. There is no effective difference between creating databases via this utility and via other methods for accessing the server.

This means that you can write a script which issues a command like

psql -f createdb.sql -v passwd=$passwd -v user=$user

Where createdb.sql contains something like

GRANT {some privileges on the newly created database and/or its objects};

This means that you will have a user for every database created.

(At the same time I have a mild suspicion that your problem is what riouj answered.)

share|improve this answer

In order to connect to your PostgreSQL instance and run the createdb script, which is a client, you can use a password file. This file is generally located at ~/.pgpass and must contain theses information :


If you want to use a different path for your password file, you can set the PGPASSFILE environment variable.

For security concerns, you can change its rights :

chmod 600 ~/.pgpass

If you don't want createdb to prompt you for any password, you can use the -w switch (or --no-password) and use the password file.

You can take a look at the documentation for these features :

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.