Postgresql: Scripting psql execution with password

Axel Fontaine picture Axel Fontaine · Jun 29, 2011 · Viewed 300k times · Source

How can I call psql so that it doesn't prompt for a password?

This is what I have:

psql -Umyuser < myscript.sql

However, I couldn't find the argument that passes the password, and so psql always prompts for it.

Answer

Reece picture Reece · Jun 29, 2011

There are several ways to authenticate to PostgreSQL. You may wish to investigate alternatives to password authentication at https://www.postgresql.org/docs/current/static/client-authentication.html.

To answer your question, there are a few ways provide a password for password-based authentication. The obvious way is via the password prompt. Instead of that, you can provide the password in a pgpass file or through the PGPASSWORD environment variable. See these:

There is no option to provide the password as a command line argument because that information is often available to all users, and therefore insecure. However, in Linux/Unix environments you can provide an environment variable for a single command like this:

PGPASSWORD=yourpass psql ...