There are two ways to non interactively provide a password for the psql command (PostgreSQL interactive terminal). Each method allows you to quickly write shell scripts using terminal-based PostgreSQL utilities as you can provide user credentials from the password file or environment variables.

Provide password using the password file

To use this method, create .pgpass file inside your home directory and restrict its permissions so it would not be ignored by utilities.

$ touch ~/.pgpass
$ chmod 0600 ~/.pgpass

Each line defines user credentials using the following structure.


Please note that every field other than a password can be replaced with an asterisk to match anything. Everything else is self-explanatory, so I will jump directly to the example.


As a user with a defined PostgreSQL password file, you can use PostgreSQL utilities without a password prompt to perform desired tasks.

$ psql -w -U milosz bookmarks -c "select * from domains"
$ pg_dump -w -c -U development -h bookmarks | \
  gzip --best > bookmarks.sql.gz

You are not forced to use the ~/.pgpass file as you can define PGPASSFILE variable to use an entirely different password file.

$ PGPASSFILE=~/.pg/.altpgpass pg_dump -c -w -U milosz bookmarks
$ export PGPASSFILE=~/.altpgpass
$ psql -w -U mediawiki -h wikidb  -c "select * from user"

As you probably noticed, I am using -w parameter, so the utilities mentioned above will fail if the password is not available.

Provide password using environment variables

Instead of using a password file, you can define PGHOST, PGPORT, PGDATABASE, PGUSER and PGPASSWORD environment variables.

  PGDATABASE=wikidb \
  PGUSER=mediawiki PGPASSWORD=631j7ZtLvSF4fyIR \
  pg_dump -w -c | gzip --best > wikidb.sql.gz
  PGUSER=development PGPASSWORD=iGsxFMziuwLdEEqw \
  psql bookmarks  -c "select * from domains"
  psql bookmarks -c "select * from favorites"