Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if mysql database exists, perform action based on result

Tags:

linux

bash

mysql

Is it possible from within a bash script to check if a mysql database exists. Depending on the result then perform another action or terminate the script?

like image 750
David Avatar asked Sep 09 '11 16:09

David


People also ask

How do you check if a database exists by listing all databases in your system?

A simple way to check if a database exists is: SHOW DATABASES LIKE 'dbname'; If database with the name 'dbname' doesn't exist, you get an empty set. If it does exist, you get one row.

How do I check if MySQL exists?

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.

How do I know which MySQL database is selected?

mysql> use test Database changed mysql> SELECT DATABASE() FROM DUAL; The following is the output. mysql> show databases; Here is the output that displays all the databases.

How do I check if a database exists?

In creating a database you also need to check whether or not the database already exists. In order to do so, simply use the 'if exists' method and select the name of the database from sysdatabases.


2 Answers

I give +1 to answer by @chown, but here's another alternative: If the bash script is running locally with the MySQL instance, and you know the path to the datadir, you can test:

if [ -d /var/lib/mysql/databasename ] ; then      # Do Stuff ... fi 

This also assumes your shell user running the script has filesystem-level privileges to read the contents of the MySQL datadir. This is often the case, but it is not certain.

like image 187
Bill Karwin Avatar answered Oct 06 '22 00:10

Bill Karwin


Example script (Thanks to Bill Karwin for the --user and --password comment!):

#!/bin/bash ## --user=XXXXXX --password=XXXXXX *may* not be necessary if run as root or you have unsecured DBs but ##   using them makes this script a lot more portable.  Thanks @billkarwin RESULT=`mysqlshow --user=XXXXXX --password=XXXXXX myDatabase| grep -v Wildcard | grep -o myDatabase` if [ "$RESULT" == "myDatabase" ]; then     echo YES fi 

These are what the commands look like when run at a prompt:

[root@host ~]# mysqlshow myDatabase Wildcard: myDatabase +------------------+ |    Databases     | +------------------+ | myDatabase       | +------------------+ 

If no DB exists, the output will look like this:

[root@host ~]# mysqlshow myDatabase Wildcard: myDatabase +-----------+ | Databases | +-----------+ +-----------+ 

Then, parse the output and do what you need to based on if it exists or not!

like image 25
chown Avatar answered Oct 06 '22 01:10

chown