0

How can I setup a new user, password and database all in one command for my PostgreSQL database? I have a test script that needs to run a command to setup a database. This is what I have tried:

psql -h localhost -U root

but this asks me to enter a password, is there a way to do it on one command i.e.

psql -h localhost -U root -P '123' - database

Where the password and new database is created?

MarkK
  • 968
  • 2
  • 14
  • 30
  • It seems not possible for security [reasons](http://stackoverflow.com/questions/6523019/postgresql-scripting-psql-execution-with-password) – tec Dec 12 '16 at 14:24

2 Answers2

1

Try something like this:

psql -U postgres -c "CREATE ROLE testuser PASSWORD 'secret' LOGIN"; psql -U postgres -c "CREATE DATABASE test"
Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
0

I presume you have sudo rights for machine/instance in question or you can connect as postgres. Command mentioned by Laurenz Albe will work only if you work as postgres and peer authentication is allowed for user postgres in pg_hba.conf file.

If you are not connected as postgres you must switch to that user - under root su postgres under other user sudo su postgres. Then command mentioned above will work.

JosMac
  • 2,164
  • 1
  • 17
  • 23