Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify a password to 'psql' non-interactively?

I am trying to automate database creation process with a shell script and one thing I've hit a road block with passing a password to psql. Here is a bit of code from the shell script:

psql -U $DB_USER -h localhost -c"$DB_RECREATE_SQL" 

How do I pass a password to psql in a non-interactive way?

like image 233
Alex N. Avatar asked Jun 19 '11 21:06

Alex N.


People also ask

What is the psql command to change the password?

Log in to psql using the postgres database login role, connecting to the postgres database. Issue the \password command to alter the passwords of the three login roles. The syntax for the \password command is \password <username>. You will be prompted to type a new password.

What is psql password?

PostgreSQL database passwords are separate from operating system user passwords. The password for each database user is stored in the pg_authid system catalog. Passwords can be managed with the SQL commands CREATE ROLE and ALTER ROLE, e.g., CREATE ROLE foo WITH LOGIN PASSWORD 'secret' , or the psql command \password .


2 Answers

Set the PGPASSWORD environment variable inside the script before calling psql

PGPASSWORD=pass1234 psql -U MyUsername myDatabaseName 

For reference, see http://www.postgresql.org/docs/current/static/libpq-envars.html


Edit

Since Postgres 9.2 there is also the option to specify a connection string or URI that can contain the username and password. Syntax is:

$ psql postgresql://[user[:password]@][host][:port][,...][/dbname][?param1=value1&...] 

Using that is a security risk because the password is visible in plain text when looking at the command line of a running process e.g. using ps (Linux), ProcessExplorer (Windows) or similar tools, by other users.

See also this question on Database Administrators

like image 159
a_horse_with_no_name Avatar answered Sep 25 '22 13:09

a_horse_with_no_name


From the official documentation:

It is also convenient to have a ~/.pgpass file to avoid regularly having to type in passwords. See Section 30.13 for more information.

...

This file should contain lines of the following format:

hostname:port:database:username:password 

The password field from the first line that matches the current connection parameters will be used.

like image 25
Flimzy Avatar answered Sep 23 '22 13:09

Flimzy