Postgresql: Scripting psql execution with password

You may wish to read a summary of the ways to authenticate to PostgreSQL.

To answer your question, there are several ways provide a password for password-based authentication:

  1. Via the password prompt. Example:

    psql -h uta.biocommons.org -U foo
    Password for user foo: 
    
  2. In a pgpass file. See libpq-pgpass. Format:

    <host>:<port>:<database>:<user>:<password>
    
  3. With the PGPASSWORD environment variable. See libpq-envars. Example:

    export PGPASSWORD=yourpass
    psql ...
    
    # Or in one line for this invocation only:
    PGPASSWORD=yourpass psql ...
    
  4. In the connection string The password and other options may be specified in the connection string/URI. See app-psql. Example:

    psql postgresql://username:password@dbmaster:5433/mydb?sslmode=require
    

PGPASSWORD=[your password] psql -Umyuser < myscript.sql