Postgresql – how to verify DB hive already exists

linuxpostgresql

by expect script we create the database hive and some other commands

in case we run the expect script again on the machine that hive already created

then we get – ERROR hive already exists

so how to verify database hive already created ?

And by this verification we can escape the expect script

# su - postgres
 Last login: Sun Aug 13 11:12:03 UTC 2017 on pts/0
 -bash-4.2$ psql
 psql (9.2.13)
 Type "help" for help.

postgres=# CREATE DATABASE hive;
ERROR:  database "hive" already exists

my expect script: ( from my bash script )

set timeout -1

#exec the scripts

spawn timeout 60 ssh root@IP
expect "#"
spawn su - postgres
expect "$"
send "psql\n"
expect "=#"
send "CREATE DATABASE hive;\n"
.
.
.
.

Best Answer

you can use IF EXISTS clause:

create database if exists hive;