Skip to content
shellhacks.dev
Databases

Connect to PostgreSQL with a psql Connection String

Connect with a URI such as postgresql://user:pass@host/db or the key=value form. Special characters in a password must be percent-encoded in the URI.

2 min read
Summarize in AI

You want to pass the whole connection in one argument, and the password contains characters like at signs or colons.

Shell
docker network create pgnet > /dev/null
docker run -d --name pgconn --network pgnet -e POSTGRES_PASSWORD=pw postgres:17-alpine > /dev/null
until [ "$(docker logs pgconn 2>&1 | grep -c 'ready to accept connections')" -ge 2 ]; do sleep 1; done
docker exec pgconn psql -U postgres -qc "create role app login password 'p@ss:w/rd'"
pg() { docker run --rm --network pgnet postgres:17-alpine psql -w "$@"; }
pg "postgresql://app:p@ss:w/rd@pgconn/postgres" -tAc "select 1" 2>&1 | tail -n 1
pg "postgresql://app:p%40ss%3Aw%2Frd@pgconn/postgres?application_name=demo" -tAc "select current_user, current_setting('application_name')"
pg "host=pgconn dbname=postgres user=app password='p@ss:w/rd'" -tAc "select current_user"
docker rm -f pgconn > /dev/null
docker network rm pgnet > /dev/null
Text
psql: error: invalid integer value "w" for connection option "port"
app|demo
app

The URI form packs user, password, host, database and options such as application_name into one string, which psql accepts as its first argument. In the URI, @, : and / have meaning, so the password p@ss:w/rd has to appear as p%40ss%3Aw%2Frd; unencoded, the run failed with invalid integer value "w" for connection option "port" because the string was split in the wrong place. The key and value form takes the password in single quotes and needs no encoding. See Connection Strings.

A password on the command line shows up in the process list and shell history, so prefer a password file or PGPASSWORD from the environment for scripts. The same string works in pg_dump and in application drivers that use libpq. This run used PostgreSQL 17.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.