When connecting to PostgreSQL with psql command, how to pass in the password?

Ordinarily, when you use psql, the console will ask you to enter the password by hand. But sometimes you may want to pass in the password in the command so that you can avoid manual operation. The most common scenario is writing a script file which needs to use psql.

Pass in the password in CLI

In the following example, we use the environment variable PGPASSWORD to pass in the password of a PostgreSQL user.

PGPASSWORD=<password> psql -h <host> -U <user> -d <db>

Please replace string in angle brackets like <password> with your own data.

Posted on 2023-03-08