List databases
List the databases on a server with psql -l, and get just the names for a script by reading the first column of psql -lqt without the headers.
You want the names of the databases on a server, and psql -l prints a wide table.
psql -lqt | cut -d'|' -f1 | sed 's/ //g' | grep .
echo ---
psql -At -c "SELECT datname FROM pg_database WHERE NOT datistemplate ORDER BY 1"postgres
template0
template1
---
postgres-l prints the list of databases and exits, and -q -t remove the extras so that each line is a row with columns separated by a pipe, as the psql reference describes. Cutting the first column gives the names, and it includes the two template databases. The query on pg_database is the exact form: it can filter templates with datistemplate.
Parsing the listing breaks if the table format changes between versions, so prefer the query in a script. A database with datallowconn set to false still appears in both outputs. Connecting needs a database to exist; postgres is the usual one, and -d template1 is the fallback.