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?
Thanks!
From the official documentation:
...
Set the PGPASSWORD environment variable inside the script before calling psql
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.
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
On Windows:
Assign value to PGPASSWORD:
C:\>set PGPASSWORD=pass
Run command:
C:\>psql -d database -U user
Ready
Or in one line,
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
I tend to prefer passing a url to psql:
This gives me the freedom to name my environment variables as I wish and avoids creating unnecessary files.
This requires
libpq
. The documentation can be found herein one line:
with command a sql command such as
"select * from schema.table"
or more readable: