63

I am using Ubuntu 12.04 and Postgress 9.2.

I need to create this user with this password e.g.

postgres://admin:[email protected]:5432

How to do that from the command line? I need to automate with a bash script. I have a fresh install.

3 Answers 3

111

This will create user admin with password test101 on localhost:

psql -c "CREATE USER admin WITH PASSWORD 'test101';"
6
  • 1
    psql -c "CREATE USER khophi WITH PASSWORD 'passo';" psql: FATAL: role "khophi" does not exist That's the error message I got. Why?
    – KhoPhi
    Nov 21, 2014 at 18:38
  • @Rexford I am not using Postgresql anymore. I suppose that psql is trying to use your username to connect to database, but you did not create any such user in database. Is this fresh install? If you are on Ubuntu, try this (alternative setup) help.ubuntu.com/community/PostgreSQL Nov 21, 2014 at 20:17
  • Yeah its fresh install. I followed the postgresql install guide on Ubuntu wiki
    – KhoPhi
    Nov 21, 2014 at 20:18
  • 11
    For future reference. When running the command, postgres needs a user from which to execute the query. To set a user different than the logged user (in this case khophi), you should use the -U flag. For example psql -U postgres -c "...". After a fresh install, you have a default superuser named postgres with no password. In ubuntu you should have done the following: $>sudo su $>su postgres $>psql -c ".... # now running as postgres user
    – Troveldom
    Jan 5, 2015 at 20:58
  • sudo su postgres . There is not need to go through the root state. May 13, 2019 at 7:53
41

To run it from any user just add the sudo -u postgres to it:

sudo -u postgres bash -c "psql -c \"CREATE USER vagrant WITH PASSWORD 'vagrant';\""
2
  • @knocte you might be right. Have you tested it without it? sudo -u postgres "psql -c \"CREATE USER vagrant WITH PASSWORD 'vagrant';\"" seems that it would work just fine.
    – mimoralea
    Dec 22, 2017 at 15:14
  • If you are running from root, you might get an error like could not change directory to "/root": Permission denied so it's better to run sudo with -i like this: sudo -i -u postgres psql -c "CREATE USER myuser WITH PASSWORD 'myuser1234';" Apr 9, 2018 at 7:34
8

To run it on the original docker image for example you can use the su -c command with the postgres user in combination with psql:

su -c "psql -c \"CREATE ROLE my_user WITH LOGIN PASSWORD 'my_password' \"" postgres

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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