I use the following modification of Arturo's solution:
psql -lqt | cut -d \| -f 1 | grep -w <db_name> | wc -l
What it does
psql -l
outputs something like the following:
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+-----------+----------+------------+------------+-----------------------
my_db | my_user | UTF8 | en_US.UTF8 | en_US.UTF8 |
postgres | postgres | LATIN1 | en_US | en_US |
template0 | postgres | LATIN1 | en_US | en_US | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | LATIN1 | en_US | en_US | =c/postgres +
| | | | | postgres=CTc/postgres
(4 rows)
Using the naive approach means that searching for a database called "List, "Access" or "rows" will succeed. So we pipe this output through a bunch of built-in command line tools to only search in the first column.
The -t
flag removes headers and footers:
my_db | my_user | UTF8 | en_US.UTF8 | en_US.UTF8 |
postgres | postgres | LATIN1 | en_US | en_US |
template0 | postgres | LATIN1 | en_US | en_US | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | LATIN1 | en_US | en_US | =c/postgres +
| | | | | postgres=CTc/postgres
The next bit, cut -d \| -f 1
splits the output by the vertical pipe |
character (escaped from the shell with a backslash), and selects field 1. This leaves:
my_db
postgres
template0
template1
grep -w
matches whole words, and so won't match if you are searching for temp
in this scenario. And the wc -l
counts matchine lines, yielding 1 if the db exists, and 0 if it doesn't.
If you'd rather follow the UNIX convention of returning an exit code rather than printing output, drop the wc
from the pipeline:
psql -lqt | cut -d \| -f 1 | grep -w <db_name>
The exit status of that pipeline will be 0
(success) if the database exists or 1
(failure) if it doesn't. Your shell will set the special variable $?
to the exit status of the last command. You can also test the status directly in a conditional:
if psql -lqt | cut -d \| -f 1 | grep -w <db_name>; then
# database exists
# $? is 0
else
# ruh-roh
# $? is 1
fi