Celeb Glow
general | April 01, 2026

Bash Script that check if a database exist

I'm trying to create a bash script that check if a database(PostgreSQL) exists:

function is_database() return $(sudo -u postgres psql -c "SELECT exists(SELECT datname FROM pg_catalog.pg_database where datname='\${1}')")
echo database:
read
is_database $REPLY

I always get(if exist or not the database):

exists ------ f (1 row)

The issue seems to be '\${1}' escaping doesn't work, and I already have outside "".

Other thing is to check the results, can be f or t.

2

1 Answer

I think return only accepts a numerical result. When I change it to echo I get the same output as you.

Using '\${1}' will pass the string ${1} to postgres, use '${1}' or '$1' (and hope that a user does not type some extra SQL to inject...)

Perhaps a different way without the need for sudo is to list the databases and grep the result:

function is_database() { psql -lqt | cut -d \| -f 1 | grep -wq $1
}
echo database:
read
if is_database $REPLY
then echo $REPLY exists
else echo $REPLY does not exist
fi

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy