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?
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:
The password field from the first line that matches the current connection parameters will be used.
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
Since Postgres 9.2 there is also the option to specify a connection string or URI that can contain the username and password.
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
Read more... Read less...
in one line:
export PGPASSWORD='password'; psql -h 'server name' -U 'user name' -d 'base name' -c 'command'
with command a sql command such as
"select * from schema.table"
or more readable:
export PGPASSWORD='password' psql -h 'server name' -U 'user name' -d 'base name' \ -c 'command' (eg. "select * from schema.table")
Assign value to PGPASSWORD:
C:\>psql -d database -U user
Or in one line,
set PGPASSWORD=pass&& psql -d database -U user
Note the lack of space before the && !
This can be done by creating a
.pgpass file in the home directory of the (Linux) User.
.pgpass file format:
You can also use wild card
* in place of details.
Say I wanted to run
tmp.sql without prompting for a password.
With the following code you can in *.sh file
echo "192.168.1.1:*:*:postgres:postgrespwd" > $HOME/.pgpass echo "` chmod 0600 $HOME/.pgpass `" echo " ` psql -h 192.168.1.1 -p 5432 -U postgres postgres -f tmp.sql `
An alternative to using the
PGPASSWORD environment variable is to use the
conninfo string according to the documentation:
An alternative way to specify connection parameters is in a conninfo string or a URI, which is used instead of a database name. This mechanism give you very wide control over the connection.
$ psql "host=<server> port=5432 dbname=<db> user=<user> password=<password>" postgres=>