How to create a user for Postgres from the command line for bash automation

PostgresqlUbuntuPostgresql 9.2

Postgresql Problem Overview


I am using Ubuntu 12.04 and Postgress 9.2.

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

postgres://admin:test101@127.0.0.1:5432

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

Postgresql Solutions


Solution 1 - Postgresql

This will create user admin with password test101 on localhost:

psql -c "CREATE USER admin WITH PASSWORD 'test101';"

Solution 2 - Postgresql

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';\""

Solution 3 - Postgresql

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTampaView Question on Stackoverflow
Solution 1 - PostgresqlTomas GreifView Answer on Stackoverflow
Solution 2 - PostgresqlmimoraleaView Answer on Stackoverflow
Solution 3 - PostgresqlaNjView Answer on Stackoverflow