Here is my bash code that checks if a db exists before I try to create one in a script:
$DBNAME="dblookingfor" DBEXISTS=$(mysql --batch --skip-column-names -e "SHOW DATABASES LIKE '"$DBNAME"';" | grep "$DBNAME" > /dev/null; echo "$?") if [ $DBEXISTS -eq 0 ];then echo "A database with the name $DBNAME already exists. exiting" exit; fi
This will exit out if there is a database with the name you are searching for. The tricky part for me (and always is) was this double quotes inside the single quotes in the LIKE statement.

Comments
6 responses to “Quick check if a mysql database exists”
Great, thanks!
You can even use “grep -q” instead o redirecting output to /dev/null.
[…] http://www.jbmurphy.com/2011/02/08/quick-check-if-a-mysql-database-exists/ this is more akin to what I […]
[…] http://www.jbmurphy.com/2011/02/08/quick-check-if-a-mysql-database-exists/ this is more akin to what I […]
[…] http://www.jbmurphy.com/2011/02/08/quick-check-if-a-mysql-database-exists/ this is more akin to what I […]
[…] http://www.jbmurphy.com/2011/02/08/quick-check-if-a-mysql-database-exists/ this is more akin to what I […]
[…] la http://www.jbmurphy.com/2011/02/08/quick-check-if-a-mysql-database-exists/ acest lucru este mai apropiat de ceea ce am […]