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 $REPLYI 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.
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