4

I am learning to use psql to work with a postgres database on linux.

I can connect using a long connection string, for example by running:

psql postgresql://myusername:mypassword@localhost:5433/dbname

However, I would like to save the details of my connection string somewhere, to simplify the command to connect to the database.

I've added the parameters to ~/.pgpass, and I've also changed the environment variables PGDATABSE, PGHOST, PGPORT, and PGUSER. However, I'm not sure how to tell psql to source connection information from either ~/.pgpass or the environment variables. When I just type psql I get an error, and I can tell from the details of the error that it is trying to connect using default parameters, like port 5432 instead of my specific port.

So how to I tell psql to use the parameters in ~/.pgpass or the environment variables? Or more broadly, how can I save my connection information to simplify the command to connect in the future?

1
  • 1
    Is the service file maybe what you are looking for?
    – user1822
    Commented Sep 28, 2020 at 17:33

1 Answer 1

3

Thanks to the comment from @a_horse_with_no_name:

Enter the details in ~/.pg_service.conf, for example:

#comment
[myconnection]
host=localhost
port=5432
user=myuser
dbname=mydb
password=mypassword

Then set a PGSERVICE environment variable specifying which connection to use

echo PGSERVICE=myconnection

Then simply entering psql should make the connection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.