Another option to pass the database password is using the PGPASSFILE
environment variable or the passfile
URI parameter.
Both expect a password file in the format
hostname:port:database:username:password
for example
localhost:5432:mydatabase:dbuser:userspassword
as described in other answers for ~/.pgpass
, but you are not confined to this specific path and and file name. This is especially useful if you need to run pg_dump
under a user that does not have a home directory, or if you want to keep all passwords in a specific location.
The location of the password file can be provided in one of the following two ways:
PGPASSFILE environment variable
Set the environment variable PGPASSFILE
before executing pg_dump
.
Example:
PGPASSFILE=/opt/custom/backup/.pgpass
pg_dump -U dbuser -w mydatabase >/var/custom/backups/pg_dump.mydatabase.sql
passfile URI parameter
If you use the URI format to provide the database, you can add the passfile
parameter to it.
Example:
pg_dump -w "postgresql://dbuser@localhost/mydatabase?passfile=/opt/custom/backup/.pgpass" >/var/custom/backups/pg_dump.mydatabase.sql
(Option -w
or --no-password
means never issue a password prompt.)